【问题标题】:List of sets, set.add() is adding to all sets in the list集合列表, set.add() 正在添加到列表中的所有集合
【发布时间】:2015-07-15 20:08:49
【问题描述】:

我正在尝试遍历电子表格并在其中创建一组所有列,同时将值添加到它们各自的集合中。

storage = [ set() ]*35 #there's 35 columns in the excel sheet
for line in in_file: #iterate through all the lines in the file
    t = line.split('\t') #split the line by all the tabs
    for i in range(0, len(t)): #iterate through all the tabs of the line
        if t[i]: #if the entry isn't empty
            storage[i].add(t[i]) #add the ith entry of the to the ith set

如果我为storage[0].add(t[0]) 执行此操作,它会起作用,但它会添加到存储列表中的所有集合中...为什么要这样做?我正在指定要添加到哪个集合。我没有发布 b/c 集合的打印输出是什么样子的,它太大了,但基本上每个集合都是相同的,并且包含选项卡中的所有条目

【问题讨论】:

标签: python list set


【解决方案1】:
storage = [set()] * 35

这将创建一个列表,其中列出了 35 次相同的集合。要创建一个包含 35 个不同集合的列表,请使用:

storage = [set() for i in range(35)]

第二种形式确保set() 被多次调用。第一种形式只调用一次,然后一遍又一遍地复制单个对象引用。

【讨论】:

    【解决方案2】:
    storage = [ set() ]*35
    
    >>>[id(i) for i in storage]
     [3055749916L,
     3055749916L,
     3055749916L,
     .....
     3055749916L]
    

    你可以看到所有都引用同一个对象。所以试试

    storage = [set() for i in range(35)]
    >>>[id(i) for i in storage]
    [3054483692L,
     3054483804L,
     .....
     3054483916L,
     3054484028L]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      相关资源
      最近更新 更多