【问题标题】:How to properly union with set如何正确地与集合联合
【发布时间】:2015-10-31 04:54:39
【问题描述】:

我知道任何带有空集的 python 集 union 都会导致它本身。但是当union 位于 for 循环内时,我会检测到一些奇怪的行为。

看起来不错

num= set([2,3,4])
emp= set()
print num|emp
>>>set([2, 3, 4])

困惑

s = set()
inp = ["dr101-mr99","mr99-out00","dr101-out00","scout1-scout2","scout3-    scout1","scout1-scout4","scout4-sscout","sscout-super"]
for ele in inp:
  r = set(ele.split("-"))
  print r
  s.union(r)
print s
 >>>set(['mr99', 'dr101'])
    set(['out00', 'mr99'])
    set(['out00', 'dr101'])
    set(['scout1', 'scout2'])
    set(['scout1', 'scout3'])
    set(['scout4', 'scout1'])
    set(['scout4', 'sscout'])
    set(['super', 'sscout'])
    set([])

谁能告诉我为什么最后一组 s 是空的? 输出应该是集合中的每个唯一元素吗?

【问题讨论】:

  • set.union 返回一个新集合,因此每次您只需将最新的ele 添加到原始(空)集合中
  • 感谢 jonrsharpe,您的评论很有帮助!
  • 在这个例子中,也可以使用s.add(r)

标签: python python-2.7 for-loop set union


【解决方案1】:

s.union(r) 是一个集合,其中包含来自sr 的元素。reference你需要改变

s.union(r)

s = s.union(r)

或者,使用set.update

【讨论】:

  • 或者使用set.update,而不是每次都创建一个新集合
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-18
相关资源
最近更新 更多