Python 如何使用列表理解来获得两个列表的并集?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20893916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:28:23 来源:igfitidea点击:
How to get the union of two lists using list comprehension?
提问by Coddy
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']
回答by CT Zhu
>>> list(set(a).union(b))
['Orange and Banana', 'Orange Banana', 'Grapes']
Thanks @abarnert
谢谢@abarnert
回答by alvas
If you have more than 2 list, you should use:
如果您有 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']

