[英]Modifying Tuples within Lists
很抱歉提出这样一个简单的问题,但我尝试搜索此站点,但仍未找到有效的答案。
我下面有元组的列表:
[('1', '1', '1', '1'), ('1', '1', '1', '2'), ('1', '1', '1', '3'),
('1', '1', '1', '4'), ('1', '1', '2', '2'), ('1', '1', '2', '3'),
('1', '1', '2', '4'), ('1', '1', '3', '3'), ('1', '1', '3', '4'),
('1', '1', '4', '4'), ('1', '2', '2', '2'), ('1', '2', '2', '3'),
('1', '2', '2', '4'), ('1', '2', '3', '3'), ('1', '2', '3', '4'),
('1', '2', '4', '4'), ('1', '3', '3', '3'), ('1', '3', '3', '4'),
('1', '3', '4', '4'), ('1', '4', '4', '4'), ('2', '2', '2', '2'),
('2', '2', '2', '3'), ('2', '2', '2', '4'), ('2', '2', '3', '3'),
('2', '2', '3', '4'), ('2', '2', '4', '4'), ('2', '3', '3', '3'),
('2', '3', '3', '4'), ('2', '3', '4', '4'), ('2', '4', '4', '4'),
('3', '3', '3', '3'), ('3', '3', '3', '4'), ('3', '3', '4', '4'),
('3', '4', '4', '4'), ('4', '4', '4', '4')]
我想用另一个名为“ List1”的列表替换所有的“ 1”。 然后我想将所有2s更改为List2,将3s更改为List3等。。。最后,我想要这样的东西:
[[[List1StuffA, List1StuffB, List1StuffC], [List1StuffA, List1StuffB, List1StuffC],
[List1StuffA, List1StuffB, List1StuffC], [List1StuffA, List1StuffB, List1StuffC]),
([List1StuffA, List1StuffB, List1StuffC], [List1StuffA, List1StuffB, List1StuffC],
[List1StuffA, List1StuffB, List1StuffC], [List2StuffA, List2StuffB, List2StuffC]),
([List1StuffA, List1StuffB, List1StuffC], [List1StuffA, List1StuffB, List1StuffC],
[List1StuffA, List1StuffB, List1StuffC], [List3StuffA, List3StuffB, List3StuffC]),
([List1StuffA, List1StuffB, List1StuffC], [List1StuffA, List1StuffB, List1StuffC],
[List1StuffA, List1StuffB, List1StuffC], [List4StuffA, List4StuffB, List4StuffC]),
...]
依此类推,其中List1 = [List1StuffA, List1StuffB, List1StuffC]
我似乎无法绕过“无法修改元组”位,而且似乎也无法将较大列表的每个元组元素更改为列表本身(并使它保持这种状态)。
我已经尝试过这样的事情:
for item in OverallList:
item = list(item)
for x in item:
x = x.replace('1', List1)
x = x.replace('2', List2)
x = x.replace('3', List3)
x = x.replace('4', List4)
但是当我打印出TotalList时,什么都没有改变。
任何帮助将不胜感激,如果我只是错过了一个可行的答案(或错误地应用了它),对不起。
您需要将您的item
重新插入到OverallList
for idx, item in enumerate(OverallList):
item = [{'1':List1, '2':List2, '3':List3, '4':List4}[k] for k in item]
OverallList[idx] = item
在for循环中执行item = list(item)
时,您将失去对OverallList
引用。 这就是为什么对item
所做的任何更改都不会反映在OverallList
中的OverallList
。 对于item
x
同样如此。
我认为,当您放置“ item = list(item)”时,您不再引用元组-“ item”是从仍在列表中的现有元组创建的列表。 尝试在循环中打印“ x”,您应该列出期望的内容。 如果是这种情况,您所需要做的就是删除元组,进行更改,然后迅速将其放回去。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.