简体   繁体   English

如何修复错误“元组索引必须是整数或切片,而不是列表”

[英]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.您想创建lm两个列表,但是使用此代码,您只是将新值重新分配给该变量。 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.

相关问题 如何修复此错误:列表索引必须是整数或切片,而不是元组 - How to fix this error: list indices must be integers or slices, not tuple 如何修复“类型错误:列表索引必须是整数或切片,而不是元组” - How to fix "TypeError: list indices must be integers or slices, not tuple" “列表索引必须是整数或切片,而不是元组”错误 - "List indices must be integers or slices, not tuple" error 错误:列表索引必须是整数或切片,而不是元组 - Error: list indices must be integers or slices, not tuple 错误是“列表索引必须是整数或切片,而不是元组” - Error is 'list indices must be integers or slices, not tuple' 如何解决“列表索引必须是整数或切片,而不是列表”错误? - How to fix ' list indices must be integers or slices, not list' error? 垂直切片:列表索引必须是整数或切片,而不是元组错误 - Vertical Slices: list indices must be integers or slices, not tuple error 如何修复“列表索引必须为整数或切片”错误 - How to fix “list indices must be integers or slices” error 处理列表会出现错误“列表索引必须是整数或切片,而不是元组” - processing a list gives the error "list indices must be integers or slices, not tuple" 类型错误“列表索引必须是整数或切片,而不是元组”(第6行) - Type error ' list indices must be integers or slices, not tuple' (line 6)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM