首页 > 解决方案 > 将元组中的元素更改为 Python 中的列表

问题描述

在 Python 代码中,我有一个这样的元组列表:

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

这是一个包含 51 个项目的列表。我必须将所有的 '-1' 更改为 '0',只要我更改它,我必须为每次更改创建一个新的元组。例如:第一个元组:[('a', -1), ('b', -1), ('c', -1)]应该生成三个不同的元组,例如: (1) [('a', 0), ('b', -1), ('c', -1)], [('a', -1), ('b', 0), ('c', -1)] and (3) [('a', -1), ('b', -1), ('c', 0)]

我尝试将所有元组转换为列表,但它不起作用。我也试过

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) 

这怎么可能解决?它不会改变任何项目。

标签: pythonlistreplacetuples

解决方案


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

推荐阅读