简体   繁体   English

Python 列表索引必须是整数或切片而不是字符串

[英]Python list indices must be integer or slice not string

image of code if not understandable代码图像如果无法理解

The image shows the code I have written, I want to swap item positions but I am getting list indices must be integer or slice not string.图像显示了我编写的代码,我想交换项目位置,但我得到的列表索引必须是整数或切片而不是字符串。 I have tried many different ways but still dont seem to get the hang of it.我尝试了许多不同的方法,但似乎仍然没有掌握它。

choice = ""
lists = []
while True:

choice = input("Try out inv commands: ")
if choice == 'inv':
    print('Backpack has ' + str(len(lists)) + ' iteams: ' + str(lists))
elif 'inv pick' in choice:
    iteams1 = choice.split('inv pick ')
    iteams2 = iteams1[1].split(' ')
    try:
        if iteams2[1] != '':
            add = lists.insert(int(iteams2[1]), iteams2[0])
            print(str(iteams2), ' has been added')
    except IndexError:
        lists.extend(iteams2)
elif 'inv drop' in choice:
    iteams1 = choice.split('inv drop ')
    iteams2 = iteams1[-1].split(' ')
    if iteams2[-1] != '':
        removed = lists.remove(iteams2[0])
        print(str(iteams2), ' has been dropped')
elif 'inv swap' in choice:
    iteams1 = choice.split('inv swap')
    iteams2 = iteams1[1].split(' ')
    try:
        if iteams2[1] != '':
            pos1, pos2 = iteams2[2], iteams2[1]
            lists[pos1], lists[pos2] = lists[pos2], lists[pos1]
            print('swapped ')
    except IndexError:
        enter code herelists.extend(iteams2)

Instead how about reversing the list?相反,如何反转列表?

lists.reverse()

If you use reversed(lists) , then it will print the list reversed.如果您使用reversed(lists) ,那么它将打印反向列表。

Well, you see, on line 30 you assigned嗯,你看,在第 30 行,你分配了

pos1, pos2 = iteams[2], iteams[1]

That means that pos1 and pos2 are string variables.这意味着pos1pos2是字符串变量。 On line 31, you tried to use lists[pos2] , but that means lists["something"] instead of lists[0] .在第 31 行,您尝试使用lists[pos2] ,但这意味着lists["something"]而不是lists[0] Always bear in mind what you value and data type assign to each variable.始终牢记您为每个变量分配的值和数据类型

As others have suggested, please follow the guideline to ask questions in stackoverflow to acommodate others in answering :)正如其他人所建议的,请按照指南在 stackoverflow 中提问以方便其他人回答:)

To answer the question, the error says that it is caused by using a string on list indexes.为了回答这个问题,错误说它是由在列表索引上使用字符串引起的。 Indeed, your variables are strings and you tried to use it in list indexes.事实上,你的变量是字符串,你试图在列表索引中使用它。 eg x[0] to get element of a list on 0th position, but not x['0']例如x[0]获取第 0 个位置的列表元素,而不是x['0']

Instead, you can try using相反,您可以尝试使用

  pos1, pos2 = int(iteams[2]), int(iteams[1]) 

but I'd suggest rewriting the code to avoid casting types and future confusions但我建议重写代码以避免转换类型和未来的混淆

As I see, you are giving strings as indices like the error mentions.正如我所看到的,您将字符串作为索引提供,就像错误提到的那样。

When you split the choice variable, it returns list of strings.当您拆分choice变量时,它返回字符串列表。 You need to convert those strings to integers or slices if you would like to access elements in those indices.如果您想访问这些索引中的元素,则需要将这些字符串转换为整数或切片。

pos1, pos2 = int(iteams2[2]),int(iteams2[-1])

This works in your case I guess.我猜这适用于你的情况。

Don't forget to paste your code to your question next time, screenshot would be hard to read for people :)下次不要忘记将您的代码粘贴到您的问题中,人们很难阅读屏幕截图:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM