How to get the union of two lists using list compr

2019-03-12 06:38发布

问题:

This question already has an answer here:

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

Consider the following lists:

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

How to get the following result:

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

回答1:

If you have more than 2 list, you should use:

>>> 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']


回答2:

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

Thanks @abarnert