【问题标题】:Modifying Tuples within Lists修改列表中的元组
【发布时间】:2012-03-13 05:21:27
【问题描述】:

对于提出如此简单的问题,我深表歉意,但我已尝试搜索此站点,但仍未找到有效的答案。

我有以下包含元组的列表:

[('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)

但是当我打印出OverallList 时,什么都没有改变。

任何帮助都将不胜感激,如果我只是错过了一个可行的答案(或错误地应用它),我很抱歉。

【问题讨论】:

  • 你能试着把你的例子浓缩成更简单的东西吗?

标签: python list tuples


【解决方案1】:

您需要将您的 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

【讨论】:

  • 是的,就是这样。我认为将字典映射移到列表组合外部会更清晰。
  • 就是这样!非常感谢!
【解决方案2】:

我认为,当您输入“item = list(item)”时,您不再引用元组——“item”是从仍在列表中的现有元组创建的列表。尝试在循环中打印“x”,您应该列出一个包含您期望的内容的列表。如果是这种情况,您需要做的就是删除元组,对其进行更改,然后将其重新放入。

【讨论】:

    【解决方案3】:

    当您在 for 循环中执行 item = list(item) 时,您将失去对 OverallList 的引用。这就是为什么对item 的任何更改都不会反映在OverallList 中。 item 中的 x 也是如此。

    【讨论】:

      猜你喜欢
      • 2013-04-26
      • 1970-01-01
      • 1970-01-01
      • 2014-06-22
      • 1970-01-01
      • 2018-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多