【问题标题】:Why union of sets does not work in a for loop in Python? [duplicate]为什么集合并集在 Python 的 for 循环中不起作用? [复制]
【发布时间】:2021-09-13 21:21:24
【问题描述】:

我有一个集合列表[{'1'}, {'2','8'}, {'3','9', '1'}]。我想遍历这个列表并找到所有这些集合的并集。我已完成以下操作,但我的集合保持为空:

my_set = set()
for i in [{'1'}, {'2','8'}, {'3','9'}]:
  print(i)
  my_set.union(set(i))
  print(my_set)
print(my_set)

输出如下:

{'1'}
set()
{'8', '2'}
set()
{'9', '3'}
set()
set()

注意: 请修复我的循环,不要提出不使用循环的快捷方式和union

【问题讨论】:

  • 联合函数返回一个集合,只需my_set = my_set.union(set(i))
  • 预期的最终结果是什么?
  • “请修复我的循环,不要提出不使用循环和联合的快捷方式”:为什么?
  • my_set.union(set(i)) 不能在原地工作,它返回一个新集。您应该为此使用.update 或增强联合运算符:myset |= i(注意,使用set(i)没有意义且效率低下)。你不应该这样做my_set = my_set.union(i),因为这将循环中效率低下
  • 这不就是my_set = {a for s in [{'1'}, {'2','8'}, {'3','9'}] for a in s}吗?

标签: python set


【解决方案1】:

union 方法返回一个新集合,但不会更改当前集合。您需要(重新)将结果分配给my_set

my_set = set()
for i in [{'1'}, {'2','8'}, {'3','9'}]:
    my_set = my_set.union(i)
print(my_set)

注意i已经是一个集合,所以不需要调用set(i)

如果您想要就地更改 my_set,请使用以下命令:

my_set = set()
for i in [{'1'}, {'2','8'}, {'3','9'}]:
    my_set.update(i)

my_set = set()
for i in [{'1'}, {'2','8'}, {'3','9'}]:
    my_set |= i

union() 接受多个集合作为参数,因此您可以执行以下操作(从一个空集合开始):

my_set = set().union({'1'}, {'2','8'}, {'3','9'})

不需要循环。

您也可以使用set.union(...) 作为类方法(来自下面的balderman 评论)而不是set().union(...)。如果您的集合列表(或元组)恰好是一个变量,则以下工作:

sets = [{'1'}, {'2','8'}, {'3','9'}]
my_set = set.union(*sets)

【讨论】:

  • 无需创建set 实例。 u = set.union({'1'}, {'2','8'}, {'3','9', '1'}) 就够了`
  • @balderman 谢谢,补充。我没有遇到文档中提到的类方法使用;不过这绝对是有道理的。
【解决方案2】:

Python 的 set 方法 X.union(Y) 返回一个新集合,它是 X 和 Y 的并集。您正在寻找 my_set.update(set(i))

当然,您可以将其写为my_set = my_set.union(set(i)),但这可能会更慢,因为它具有不同的语义(.update() 使用就地添加方法,而 union 将构造一个额外的副本。)

【讨论】:

    【解决方案3】:

    你必须重新分配联合返回的值

    my_set = set()
    for i in [{'1'}, {'2','8'}, {'3','9'}]:
      print(i)
      my_set = my_set.union(set(i))
      print(my_set)
    print(my_set)
    

    【讨论】:

      【解决方案4】:

      使用my_set.update(i) 而不是联合。顺便说一句,您不需要set(i),因为i 已经是一个集合。如果i 是一个列表,它也可以在不强制转换的情况下工作。

      鉴于i 是一个集合,您也可以将其写为:

      my_set |= i
      

      甚至可以在一行中完成所有操作:

      my_set = set().union(*[{'1'}, {'2','8'}, {'3','9', '1'}]) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-17
        • 2021-05-16
        • 1970-01-01
        • 2010-10-17
        • 2021-05-22
        • 2014-04-27
        • 1970-01-01
        • 2015-01-22
        相关资源
        最近更新 更多