Home > Mobile >  Changing elements in a tuple converted to list in Python
Changing elements in a tuple converted to list in Python

Time:09-26

In a Python code, I have a list of tuples like that:

file1 = [[('a', -1), ('b', -1), ('c', -1)], [('a', -1), ('b', -1), ('c', 0)], [('a', -1), ('b', -1), ('c', 1)], [('a', 0), ('b', -1), ('c', 1)]] 

It is a list with 51 items. I have to change all of the '-1' for '0', and as long as I change it, I have to create a new tuple for each change. For example: the first tuple: [('a', -1), ('b', -1), ('c', -1)] should generate three different tuples like: (1) [('a', 0), ('b', -1), ('c', -1)], [('a', -1), ('b', 0), ('c', -1)] and (3) [('a', -1), ('b', -1), ('c', 0)].

I tried by converting all tuples into lists but it is not working. I tried also

for i in file1:
    i = list(i)
    for j in i:
        j = list(j)
        if j[1] == -1:
            j = (j[0],0)
            file2.append(i) 

How this could be solved? It is not changing any item.

CodePudding user response:

from copy import deepcopy

# somewhere to save results
file2 = []

# loop the outer list
for inner_list in file1:

  # save the original (or remove, if not needed)
  file2.append(inner_list)

  # loop the individual tuples
  for i, t in enumerate(inner_list):

    # find any -1s
    if t[1] == -1:

      # save the list, again
      file2.append(deepcopy(inner_list))

      # replace the required tuple
      file2[-1][i] = tuple([t[0], 0])
      

CodePudding user response:

It doesn't make any changes, because each time you append i. And you're also iterating over the sublist items, but don't actually store the whole new changed sublist anywhere. Instead, when you iterate over the items of the sublist and encounter a -1, create a copy of the sublist, change the value to 0 at that index and append this new copy to the result.

file1 = [[('a', -1), ('b', -1), ('c', -1)], [('a', -1), ('b', -1), ('c', 0)], [('a', -1), ('b', -1), ('c', 1)], [('a', 0), ('b', -1), ('c', 1)]]

file2 = []
for items in file1:
    for i, (_, value) in enumerate(items):
        if value == -1:
            tmp = items.copy()
            tmp[i] = (tmp[i][0], 0)
            file2.append(tmp)
  • Related