本文介绍了Itertools.chain.from_iterable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以向我解释一下此代码段到底在做什么?

Can anyone explain to me, what exactly this code snippet is doing?

chained_country_list = set(itertools.chain.from_iterable(country_and_countrycodes)) & set(all_countries)

我知道它在彼此之间运行两个列表,最后得到一组唯一的值,该值存在于它比较的两个列表中.

I know it runs two lists against each other, ending up with a set of unique values, that exists in both the lists it compares.

但是它是如何做到的,以及幕后发生的一切使我感到困惑.

But how it does it, and whats happening under the hood, confuses me.

如果有人可以在这个问题上分享一些看法,将会有很大的帮助.

Would be a huge help if someone could share some light on the issue.

推荐答案

让我们分解代码的每个重要元素:

Let's break down each significant element of the code:

itertools.chain.from_iterable:

基本上,这用于展平嵌套列表,如下所示:

Basically, this is used to flatten a nested list, like this:

l = [[0], [1, 2], [2], [3, 6], [4], [5, 10]]
list(itertools.chain.from_iterable(l))

输出:

[0, 1, 2, 2, 3, 6, 4, 5, 10]

两组之间的

&运算符:

& operator between two sets:

请考虑以下关于集合a和b的示例.

Consider the follow example of sets a and b.

a = {1, 2, 3}
b = {2, 3, 4}
a & b

输出:

{2, 3}

因此,基本上,它获得了两个集合之间的公共元素.这是2和3.

So basically it gets the common elements between two sets. Here they're 2 and 3.

整个代码:

让我们说:

country_and_countrycodes = [('United States', 'US'), ('China', 'CH')]
all_countries = ['United States', 'Mongolia', 'Togo']

现在,第一部分是:

set(itertools.chain.from_iterable(country_and_countrycodes))

这给了我们

{'CH', 'China', 'US', 'United States'}

因此,它只是为我们从元组中获取了一个扁平集.

So, it just gets us a flat set from the tuples.

然后,第二部分是:

set(itertools.chain.from_iterable(country_and_countrycodes)) & set(all_countries)

这给了我们

{'United States'}

基本上,我们所做的是:

Basically, what we did was:

{'CH', 'China', 'US', 'United States'} & {'United States', 'Mongolia', 'Togo'}

由于这里唯一的共同元素是'United States',所以这就是我们得到的输出.

Since the only common element here is 'United States', that's what we got as the output.

这篇关于Itertools.chain.from_iterable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:30