Itertools.chain.from_iterable

前端 未结 2 989
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-22 07:46

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

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


        
2条回答
  •  旧时难觅i
    2021-01-22 08:37

    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))    
    

    Output:

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

    & operator between two sets:

    Consider the follow example of sets a and b.

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

    Output:

    {2, 3}
    

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

    The code as a whole:

    Let's say:

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

    Now, the first part is:

    set(itertools.chain.from_iterable(country_and_countrycodes))
    

    which gives us:

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

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

    Then, the second part is:

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

    which gives us:

    {'United States'}
    

    Basically, what we did was:

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

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

提交回复
热议问题