Python 如何在不使用“|”的情况下将两组合并为一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17429123/
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
How to join two sets in one line without using "|"
提问by fandyst
Assume that S
and T
are assigned sets. Without using the join operator |
, how can I find the union of the two sets? This, for example, finds the intersection:
假设S
和T
被分配了集合。不使用连接运算符|
,如何找到两个集合的并集?例如,这会找到交集:
S = {1, 2, 3, 4}
T = {3, 4, 5, 6}
S_intersect_T = { i for i in S if i in T }
So how can I find the union of two sets in one line without using |
?
那么如何在不使用的情况下在一行中找到两个集合的并集|
?
回答by arshajii
Assuming you also can't use s.union(t)
, which is equivalent to s | t
, you could try
假设你也不能使用s.union(t)
,相当于s | t
,你可以试试
>>> from itertools import chain
>>> set(chain(s,t))
set([1, 2, 3, 4, 5, 6])
Or, if you want a comprehension,
或者,如果你想要理解,
>>> {i for j in (s,t) for i in j}
set([1, 2, 3, 4, 5, 6])
回答by BenjaminCohen
If by join you mean union, try this:
如果加入你的意思是联合,试试这个:
set(list(s) + list(t))
It's a bit of a hack, but I can't think of a better one liner to do it.
这有点麻烦,但我想不出更好的衬里来做到这一点。
回答by ovrwngtvity
You can use union method for sets: set.union(other_set)
您可以对集合使用联合方法: set.union(other_set)
Note that it returns a new set i.e it doesn't modify itself.
请注意,它返回一个新集合,即它不会修改自身。
回答by Alexander Klimenko
You could use or_
alias:
您可以使用or_
别名:
>>> from operator import or_
>>> from functools import reduce # python3 required
>>> reduce(or_, [{1, 2, 3, 4}, {3, 4, 5, 6}])
set([1, 2, 3, 4, 5, 6])
回答by iyogeshjoshi
Suppose you have 2 lists
假设您有 2 个列表
A = [1,2,3,4]
B = [3,4,5,6]
so you can find A
Union B
as follow
所以你可以找到A
UnionB
如下
union = set(A).union(set(B))
also if you want to find intersection and non-intersection you do that as follow
另外,如果你想找到交集和非交集,你可以按照以下方式进行
intersection = set(A).intersection(set(B))
non_intersection = union - intersection
回答by Vaibhav Mishra
You can do union
or simple list comprehension
你可以做union
或简单的列表理解
[A.add(_) for _ in B]
A would have all the elements of B
A 将拥有 B 的所有元素
回答by Max Candocia
If you are fine with modifying the original set (which you may want to do in some cases), you can use set.update()
:
如果您可以修改原始集(在某些情况下您可能想要这样做),则可以使用set.update()
:
S.update(T)
The return value is None
, but S
will be updated to be the union of the original S
and T
.
返回值是None
,但S
将更新为原始S
和 的并集T
。
回答by Jamie Saunders
you can just unpack both sets into one like this:
你可以像这样将两套解压成一套:
>>>set_1 = {1, 2, 3, 4}
>>>set_2 = {3, 4, 5, 6}
>>>union = {*set_1, *set_2}
>>>union
{1, 2, 3, 4, 5, 6}