python - 将元组中的元素更改为 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)
这怎么可能解决?它不会改变任何项目。
解决方案
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])
推荐阅读
- python - Python Tkinter 中“after”方法的问题
- java - 如何创建扩展 AuditingEntityListener 的自定义审计实体侦听器
- laravel - 如何使用 vue 和 laravel 在数据库中存储 null?
- elasticsearch - ELK:通过 filebeat 更改字段格式
- swift - 如何在xcode中添加动态框架
- c++ - 为什么超出内存限制?
- ruby-on-rails - 失败/错误:expect(response.status).to eq(200) rspec
- verification - 为什么在验证模式下,我的代码不会抛出违反断言?普罗米拉
- substrate - 在墨水智能合约部署中生成的代码哈希
- python - 如何使宽格式的数据框从现有的列名中创建新的列名?