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

O.r*_*rka 2 python list set

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

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
Run Code Online (Sandbox Code Playgroud)

如果我这样做storage[0].add(t[0])它的工作种类,但它添加到存储列表中的所有集...为什么它这样做?我正在指定我要添加它的集合.我没有发布打印出来的集合b/c它是如此之大但基本上每个集都是相同的并且具有来自标签的所有条目

Joh*_*ica 8

storage = [set()] * 35
Run Code Online (Sandbox Code Playgroud)

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

storage = [set() for i in range(35)]
Run Code Online (Sandbox Code Playgroud)

第二种形式确保set()被多次调用.第一种形式只调用一次,然后反复复制该单个对象引用.