Pythonic Way to Create Union of All Values Contained in Multiple Lists

泄露秘密 提交于 2019-11-26 22:36:40
sth

set.union does what you want:

>>> results_list = [[1,2,3], [1,2,4]]
>>> results_union = set().union(*results_list)
>>> print(results_union)
set([1, 2, 3, 4])

You can also do this with more than two lists.

Since you seem to be using Python 2.5 (it would be nice to mention in your Q if you need an A for versions != 2.6, the current production one, by the way;-) and want a list rather than a set as the result, I recommend:

   import itertools

   ...

   return list(set(itertools.chain(*result_list)))

itertools is generally a great way to work with iterators (and so with many kinds of sequences or collections) and I heartily recommend you become familiar with it. itertools.chain, in particular, is documented here.

I used the following to do intersections, which avoids the need for sets.

a, b= [[1,2,3], [1,2]]
s = filter( lambda x: x in b, a)

or,

s = [ x for x in b if x in a ]

Unions are not supported by lists, which are ordered, but are supported by sets. Check out set.union.

You can also follow this style

In [12]: a = ['Orange and Banana', 'Orange Banana']
In [13]: b = ['Grapes', 'Orange Banana']
In [14]: c = ['Foobanana', 'Orange and Banana']

In [20]: list(set(a) | set(b) | set(c))
Out[20]: ['Orange and Banana', 'Foobanana', 'Orange Banana', 'Grapes']

In [21]: list(set(a) & set(b) | set(c))
Out[21]: ['Orange and Banana', 'Foobanana', 'Orange Banana']    
Mike G.
desired_result = [x for y in lists for x in y]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!