简体   繁体   English

设置并集,列表理解

[英]Set union, List Comprehensions

I'm getting started with Python and currently learning about list comprehensions so this may sound really strange. 我正在开始使用Python,目前正在学习列表推导,因此这听起来确实很奇怪。

Question: Is it possible to use list comprehension to create a list of elements in t and s without duplicates? 问题:是否可以使用列表推导在t和s中创建没有重复的元素列表? Sort of like union of two sets but using lists instead...? 有点像两个集合的并集,但是使用列表...?

I use basic python so I'm not allowed use any shortcut 'reserved' words... 我使用基本的python,所以不允许使用任何快捷方式“保留”字...

In fact, you're trying to do an union of two sets . 实际上,您正在尝试进行两个集合的并集 Use set/frozenset datatype to do this, not list comprehension : 使用set / frozenset数据类型执行此操作,而不是列出理解:

>>> t = ['a', 'b', 'c']
>>> s = ['b', 'd', 'e']
>>> u = set(t)
>>> v = set(s)
>>> u
set(['a', 'c', 'b'])
>>> v
set(['b', 'e', 'd'])
>>> u | v
set(['a', 'c', 'b', 'e', 'd'])
>>> u.union(v)
set(['a', 'c', 'b', 'e', 'd'])
>>> u.union(s)                
set(['a', 'c', 'b', 'e', 'd'])

See this SO answer for more information. 有关更多信息,请参见此SO答案

Yes, it's possible to "union" two lists: 是的,可以“合并”两个列表:

>>> s = [1,2,3,4]
>>> t = [3,5,4,7]
>>> 
>>> s + [x for x in t if x not in s]
[1, 2, 3, 4, 5, 7]

However, this is bad Python, because the comprehension part will scan the whole list s for each element in t . 但是,这是不好的Python,因为理解部分将扫描整个列表st每个元素。 In real code, you should use sets, as @Jérôme showed. 在实际代码中,您应该使用集合,如@Jérôme所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM