0

我创建了一个函数,并向函数传递了一个字符串列表,如下所示: ['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'XX']

我创建了一个具有 26 个值的变量 X;我在下面的代码中将这些值称为“卡片”(“用于 X 中的卡片”)。

我正在使用 itertools 和列表推导来创建一个字符串列表,以便 X 中的每个值都替换为新列表中的“XX”。

例如:['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'XX']将扩展为['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'value1'], ['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'value2'] etc

我正在创建一个名为 tmp 的值列表,并使用 for 循环将“X”值列表(称为卡)替换 tmp 中的一个项目(称为“XX”)。

 unitoffive = list(itertools.combinations(unit,5))
 newunit = [list(line) for line in unitoffive if 'XX' in line]


 tmp = [[line,card] for line in newunit for card in X]
 for line in tmp:
     line[0][4] = line.pop(line.index(line[1]))
     print line

  for line in tmp:
     print line

我的脚本表现出我无法理解的行为。当我的第一个 for 循环中的打印行语句被执行时,我看到了我期望的修改列表。当调用第二个打印行语句时,我看到了另一个不正确的列表版本。我无法返回和使用 tmp,因为它似乎只在修改它的 for 循环中包含正确的值。

我知道在 for 循环中修改 Python 列表可能很棘手,我尝试将代码更改为循环,for line in tmp[:]但这并没有解决我的问题。

这部分代码中的打印行语句['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'value1'], ['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'value2'] etc按预期打印:

for line in tmp:
  line[0][4] = line.pop(line.index(line[1]))
  print line

其后的打印行语句打印['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'value26'], ['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'value26'] etc

4

1 回答 1

1

You're changing the [line, card] sublists and expecting the tmp list to have a copy of them, not the same objects. Try changing:

for line in tmp:

For:

import copy
for line in copy.deepcopy(tmp):

And see if it works as you expect.

edit

It seems like this is what you want, to append to the inlist instead of inserting:

>>> line = [['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'XX'], ['value1']]
>>> line[0].append(line.pop()[0])
>>> line
[['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'XX', 'value1']]
>>> 
于 2012-04-21T21:15:21.483 回答