我正在做一项作业,要求我进行代码演练。我想简要说明一下 set().union(*list1) 的工作原理,以便我在演练期间回答。
list1 = [[1,2,3],[1,2,3,5,8]]
x = set().union(*list1)
print(list(x))
#output = [1, 2, 3, 5, 8]
最佳答案
来自文档:https://docs.python.org/3/library/stdtypes.html#frozenset.union
union(*others)
set | other | ...
Return a new set with elements from the set and all others.
*list
也叫列表拆包,我们得到列表里面的两个子列表
In [37]: list1 = [[1,2,3],[1,2,3,5,8]]
In [38]: print(*list1)
[1, 2, 3] [1, 2, 3, 5, 8]
因此,您运行的代码实际上创建了列表 x
中所有子列表的并集,并且由于您知道集 [1,2,3]
的并集> 和 [1,2,3,5,8]
是 [1,2,3,5,8]
,因此是预期的结果。
请注意,这相当于 list(set([1,2,3]).union(set([1,2,3,5,8])))
我们在这里做 a.union(b)
,a
和 b
被设置
In [31]: list1 = [[1,2,3],[1,2,3,5,8]]
...:
...: x = set().union(*list1)
In [32]: print(list(x))
[1, 2, 3, 5, 8]
In [33]: print(list(set([1,2,3]).union(set([1,2,3,5,8]))))
[1, 2, 3, 5, 8]
除此之外,执行union
甚至intersection
的更好方法可能是使用map( set,list1)
,展开集合,然后进行操作
In [39]: list1 = [[1,2,3],[1,2,3,5,8]]
In [40]: print(set.intersection(*map(set,list1)))
{1, 2, 3}
In [41]: print(set.union(*map(set,list1)))
{1, 2, 3, 5, 8}
关于python - 为什么 set().union(*list1) 给我一个列表中两个列表的并集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56052104/