python - 为什么 set().union(*list1) 给我一个列表中两个列表的并集?

标签 python python-3.x set argument-unpacking set-union

我正在做一项作业,要求我进行代码演练。我想简要说明一下 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)ab 被设置

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/

相关文章:

python - 具有循环依赖的 GraphQL 设计

python - 使用sklearn一键编码后如何给出列名?

python - 数据操作 - 当值为字母数字时排序索引

python - 不能将 librosa 与 python 3 一起使用

python - 从特定表格元素中抓取特定文本时返回错误数据

c++ - 有一个只有文件名(a、f/a、f/b、f/f/c 等)的 std::set 如何通过给定的 f/列出目录?

java - 爬取时如何从大量数据中消除重复

python - 我正在尝试使用 Twython 从 Python 上的 Twitter 查询中提取推文

python - 当一个包含 id 而第二个包含与该 id 关联的名称时,需要帮助合并两个 SQL 表

python - 获取 3 个列表之间的差异