14

我在使用集合列表时遇到问题,我认为这是因为我将其初始化错误,这是初始化并添加到 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])

任何建议将不胜感激

4

2 回答 2

28

您正在每个列表索引中存储对单个集合的引用副本。所以,修改一个也会改变其他的。

要创建多个集合的列表,您可以使用列表推导:

sets = [set() for _ in xrange(5000)]
于 2013-07-12T17:22:58.707 回答
9

这有效:

>>> 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']]
于 2013-07-12T17:24:09.687 回答