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

标签 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

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

最佳答案

storage = [set()] * 35

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

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

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

关于python - 集合列表,set.add() 正在添加到列表中的所有集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31440056/

相关文章:

c++ - std::set 的运算符重载无法正常工作

python - 如何将 matlab 代码转换为 python 代码?

python - 从多索引数据框中选择列,例如制作直方图

python - 导入错误 : cannot import name suppress

python - 替换列表中的元素

list - F# 匹配模式鉴别器未定义问题

python - Python中集合的迭代顺序

algorithm - 用 getRandom 设置

python - 在 Python 3.6 中追加迭代时重复元素

java - 为什么我们不能增加 asList() 返回的 ArrayList 对象的大小?