集合列表,set.add() 正在添加到列表中的所有集合

List of sets, set.add() is adding to all sets in the list

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

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]) 执行此操作,它可以工作,但它会添加到存储列表中的所有集合中...为什么要这样做?我正在指定要添加到哪个集合中。我没有 post 集合的打印输出看起来如何 b/c 它太大了,但基本上每个集合都是相同的并且具有所有选项卡中的条目

storage = [set()] * 35

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

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

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

storage = [ set() ]*35

>>>[id(i) for i in storage]
 [3055749916L,
 3055749916L,
 3055749916L,
 .....
 3055749916L]

你可以看到所有的都引用相同的 object.So try

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