【问题标题】:TypeError: list indices must be integers or slices, not tuple for list of tuplesTypeError:列表索引必须是整数或切片,而不是元组列表的元组
【发布时间】:2017-09-18 09:16:15
【问题描述】:

我在尝试从元组列表生成列表时收到“列表索引必须是整数或切片,而不是元组”错误。 元组列表具有以下结构:

[(29208, 8, 8, 8), (29209, 8, 8, 8), (29210, 8, 8, 8), (29211, 8, 8, 8)]

元组中的第一个元素是时间序列,其他元素是一些变量的状态。

从元组列表转换为简单列表的循环如下:

TimeAxis = []

for n in lst:
    TimeAxis.append(lst[n][0])

其中 lst 具有如上所述的格式。 由于某种原因,它会引发错误:

Traceback (most recent call last):
  File "X:\Temp\XXX_python_graph\RTT_Plot.py", line 30, in <module>
    Time.append(lst[n][0])
TypeError: list indices must be integers or slices, not tuple

我知道这是一个新手问题,但 stackoverflow 上的其他解决方案不起作用。 提前致谢。

【问题讨论】:

标签: python list tuples


【解决方案1】:

Python 的for 循环是Foreach construct;您遍历列表的元素,而不是索引。

所以n 是来自lst 的元组之一,而不是索引。直接使用:

for n in lst:
    TimeAxis.append(n[0])

您可以使用list comprehension 来简化您的代码:

TimeAxis = [tup[0] for tup in lst]

【讨论】:

    【解决方案2】:
    for n in lst:
        TimeAxis.append(n[0])
    

    当您在列表上迭代时,它会一个一个地获取元素,因此n 的值是您的每个元组,只需访问它的0th 索引并附加

    【讨论】:

      【解决方案3】:

      让我帮你了解一下,你的代码出了什么问题:

      lst = [(29208, 8, 8, 8), (29209, 8, 8, 8), (29210, 8, 8, 8), (29211, 8, 8, 8)]
      for n in lst:  # ns in lst -> (29208, 8, 8, 8), ... , (29211, 8, 8, 8)
          TimeAxis.append(lst[n][0]) # 1st iter: lst[(29208, 8, 8, 8)][0]
      

      因此TypeError。您可能想要做的是:

      for i in range(len(lst)):  # is in range(len(lst)) -> 0,1,2,3 
          TimeAxis.append(lst[n][0])  # 1st iter: lst[0][0]
      

      即使这样可行,也没有必要这样做。还有更多的pythonic方式,可以在@Martijn Pieters answer找到。

      【讨论】:

        猜你喜欢
        • 2017-10-02
        • 2019-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-27
        • 1970-01-01
        相关资源
        最近更新 更多