簡體   English   中英

集合列表,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])它的工作方式有點但它會添加到存儲列表中的所有集合...為什么這樣做呢? 我正在指定我要添加它的集合。我沒有發布打印出來的集合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]

你可以看到所有都引用同一個對象。所以試試

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM