如何使用列表理解获得两个列表的并集?

时间:2014-01-02 23:31:06

标签: python list-comprehension

请考虑以下列表:

a = ['Orange and Banana', 'Orange Banana']
b = ['Grapes', 'Orange Banana']

如何获得以下结果:

c = ['Orange and Banana', 'Orange Banana', 'Grapes']

2 个答案:

答案 0 :(得分:58)

如果您有超过2个列表,则应使用:

>>> a = ['Orange and Banana', 'Orange Banana']
>>> b = ['Grapes', 'Orange Banana']
>>> c = ['Foobanana', 'Orange and Banana']
>>> list(set().union(a,b,c))
['Orange and Banana', 'Foobanana', 'Orange Banana', 'Grapes']

答案 1 :(得分:9)

>>> list(set(a).union(b))
['Orange and Banana', 'Orange Banana', 'Grapes']

谢谢@abarnert