[英]how to fix error "tuple indices must be integers or slices, not list"
i have this code我有这个代码
#fsa and ghf are both lists of equal length
#this code divides each of the elements within each list into multiple lists in six element intervals
start = 0
end = len(fsa)
for x in range(start,end,6):
l = fsa[x:x+6], [x]
m = ghf[x:x+6], [x]
# this code should be able to fetch the first and last element in those lists of six for 'ghf'(but i can't seem to make it work)
for x in m:
m1 = m[x]
m2 = m[x+5]
print(m1, m2)
Whenever i run that last code i get this error每当我运行最后一个代码时,我都会收到此错误
Traceback (most recent call last):
File "C:\Users\nkosi\PycharmProjects\Fmark 1\venv\mark 1.py", line 53, in <module>
m1 = m[x]
TypeError: tuple indices must be integers or slices, not list
please help me resolve this issue.请帮我解决这个问题。
m
is a tuple and x
is a list. m
是一个元组, x
是一个列表。
You can't index a tuple with a list.你不能用列表索引一个元组。 You have to use an int or slice.您必须使用 int 或 slice。
you want to make l
and m
two lists, but with this code you're just reassigning new values to that variables.您想创建l
和m
两个列表,但是使用此代码,您只是将新值重新分配给该变量。 so you have at first to declare them:所以你首先要声明它们:
start = 0
end = len(fsa)
l = []
m = []
and then append values to the lists:然后将值附加到列表中:
for x in range(start,end,6):
l.append(fsa[x:x+6])
m.append(ghf[x:x+6])
then, if you want to take the first and last element (I'll do as in the example, where you only want the first and last of each element of m
, and not also of l
), given that the length of each little list is 6:那么,如果你想取第一个和最后一个元素(我会像例子中那样做,你只想要m
的每个元素的第一个和最后一个,而不是l
的),假设每个小元素的长度清单是 6:
for x in m:
m1 = m[0]
m2 = m[5]
print(m1, m2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.