我在设置列表时遇到问题,我认为这是因为我初始化错了,这是一种初始化并添加到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])
任何建议都将不胜感激
答案 0 :(得分:18)
您正在将参考副本存储到每个列表索引中的单个集合中。因此,修改一个也将改变其他人。
要创建多个集合的列表,可以使用列表解析:
sets = [set() for _ in xrange(5000)]
答案 1 :(得分:5)
这有效:
>>> 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]*5000
是不可变的,那么您应该只使用x
形式:
>>> 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']]