[英]TypeError: list indices must be integers or slices, not tuple for list of tuples
I am getting "list indices must be integers or slices, not tuple" error while trying to generate list from list of tuples. 尝试从元组列表生成列表时,出现“列表索引必须是整数或切片,而不是元组”错误。 list of tuples have the following structure:
元组列表具有以下结构:
[(29208, 8, 8, 8), (29209, 8, 8, 8), (29210, 8, 8, 8), (29211, 8, 8, 8)]
The first element in the tuple is a time series, other elements are state of some variables. 元组中的第一个元素是时间序列,其他元素是某些变量的状态。
The loop for converting from list of tuples to simple list is following: 从元组列表转换为简单列表的循环如下:
TimeAxis = []
for n in lst:
TimeAxis.append(lst[n][0])
Where lst has format as described above. 其中lst具有如上所述的格式。 For some reason it throws an error:
由于某种原因,它将引发错误:
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
I understand this is novice question, but other solutions on stackoverflow do not work. 我了解这是新手问题,但是关于stackoverflow的其他解决方案不起作用。 Thanks in advance.
提前致谢。
Python's for
loop is a Foreach construct ; Python的
for
循环是一个Foreach构造 ; you iterate over the elements of the list , not an index. 您遍历列表的元素 ,而不是索引。
So n
is one of the tuples from lst
, not an index. 所以
n
是lst
中的元组之一,而不是索引。 Use it directly: 直接使用:
for n in lst:
TimeAxis.append(n[0])
You could simplify your code by using a list comprehension : 您可以通过使用列表理解来简化代码:
TimeAxis = [tup[0] for tup in lst]
for n in lst:
TimeAxis.append(n[0])
When you iterate on list, its fetching one by one element, so value of n
is your every tuple, just access 0th
index of it and append 当您在列表上进行迭代时,它会逐个获取元素,因此
n
值是您的每个元组,只需访问它的0th
索引并追加
let me help you understand, what has gone wrong in your code: 让我帮助您了解代码中出了什么问题:
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]
Hence the TypeError
. 因此,
TypeError
。 What you probably wanted to do is: 您可能想做的是:
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]
Even though this will work, there is no need for that. 即使这行得通,也没有必要。 There are more pythonic way, which can be found in @Martijn Pieters answer .
还有更多的pythonic方式,可以在@Martijn Pieters answer中找到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.