[英]making an array of sets in python
我在設置列表時遇到問題,我認為這是因為我初始化錯了,這是一種初始化並添加到5000集列表的有效方法嗎?
sets = [set()]*5000
i = 0
for each in f:
line = each.split()
if (some statement):
i = line[1]
else:
sets[i].add(line[0])
任何建議將不勝感激
您正在將引用的副本存儲到每個列表索引中的單個集合中。 因此,修改一個也將改變其他人。
要創建多個集的列表,可以使用列表解析:
sets = [set() for _ in xrange(5000)]
這有效:
>>> lotsosets=[set() for i in range(5)]
>>> lotsosets
[set([]), set([]), set([]), set([]), set([])]
>>> lotsosets[0].add('see me?')
>>> lotsosets
[set(['see me?']), set([]), set([]), set([]), set([])]
>>> lotsosets[1].add('imma here too')
>>> lotsosets
[set(['see me?']), set(['imma here too']), set([]), set([]), set([])]
如果x
是不可變的,你應該只使用[x]*5000
形式:
>>> li=[None]*5
>>> li
[None, None, None, None, None]
>>> li[0]=0
>>> li
[0, None, None, None, None]
>>> li[1]=1
>>> li
[0, 1, None, None, None]
或者,如果對單個項目(如迭代器)進行多次引用,則會產生所需的行為:
>>> [iter('abc')]*3
[<iterator object at 0x100498410>,
<iterator object at 0x100498410>,
<iterator object at 0x100498410>] # 3 references to the SAME object
注意重復引用相同的迭代器,然后使用zip產生所需的行為:
>>> zip(*[iter('abcdef')]*3)
[('a', 'b', 'c'), ('d', 'e', 'f')]
或者是更長迭代器的子集:
>>> [next(x) for x in [iter('abcdef')]*3]
['a', 'b', 'c']
而像[list()]*5
這樣的東西可能不會產生預期的東西:
>>> li=[list()]*5
>>> li
[[], [], [], [], []]
>>> li[0].append('whoa')
>>> li
[['whoa'], ['whoa'], ['whoa'], ['whoa'], ['whoa']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.