简体   繁体   中英

Changing the value of an item in a list in a Python for loop

I have created a function and am passing the function a list of strings like this: ['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'XX']

I have created a variable X with 26 values; I refer to these values as 'card' in my code below ('for card in X').

I am using itertools and list comprehensions to create a list of strings so that each value in X is substituted for 'XX' in a new list.

For example: ['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'XX'] will expand to ['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'value1'], ['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'value2'] etc

I am creating a list of values called tmp and substituting the list of 'X' values (called card) for one of the items in tmp (called 'XX') using a for loop.

 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

My script is exhibiting behavior I cannot understand. When the print line statement in my first for loop is executed I see the modified list that I expect. When the second print line statement is called I see another and incorrect version of my list. I can't return and use tmp since it only seems to contain the correct values within the for loop in which it was modified.

I know that Python lists can be tricky to modify in a for loop and I tried changing my code to loop over for line in tmp[:] but that didn't solve my problem.

The print line statement in this section of code prints ['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'value1'], ['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'value2'] etc as expected:

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

The print line statement following it prints ['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'value26'], ['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'value26'] etc

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']]
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM