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

发布于 2025-02-10 23:32:57 字数 754 浏览 1 评论 0原文

我都会有此代码

#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)

每当运行最后一个代码时,

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

,我会收到此错误,请帮助我解决此问题。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南汐寒笙箫 2025-02-17 23:32:58

m是元组,x是列表。

您不能将元组与列表索引。您必须使用int或切片。

m is a tuple and x is a list.

You can't index a tuple with a list. You have to use an int or slice.

楠木可依 2025-02-17 23:32:58

您需要制作lm两个列表,但是使用此代码,您只需将新值重新分配到该变量。因此,您首先必须声明它们:

start = 0
end = len(fsa)
l = []
m = []

然后将值附加到列表中:

for x in range(start,end,6):
    l.append(fsa[x:x+6])
    m.append(ghf[x:x+6])

然后,如果您想采用第一个和最后一个元素(我会像在示例中一样,您只需要每个元素的第一个和最后一个元素m,而不是l),鉴于每个小列表的长度为6:

for x in m:
    m1 = m[0]
    m2 = m[5]

    print(m1, m2)

you want to make l and m two lists, but with this code you're just reassigning new values to that variables. 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:

for x in m:
    m1 = m[0]
    m2 = m[5]

    print(m1, m2)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文