gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:20:25 30 4
gpt4 key购买 nike

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

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com