简体   繁体   English

Python 错误:列表索引必须是整数或切片,而不是 str

[英]Python Error : list indices must be integers or slices, not str

I tried to remove duplicates of a list using set method and add that value with a key to an empty python dictionary.我尝试使用set方法删除列表的重复项,并将该值与一个键添加到一个空的 python 字典中。

But it gives me that error message但它给了我那个错误信息

TypeError: list indices must be integers or slices, not str

I tried this way:我试过这种方式:

mydir =[]
person_trackID = "p7"
class_ids = [3 ,3 ,3 ]
print(mydir,person_trackID,set(class_ids))
mydir[person_trackID] = list(set(class_ids))
print(mydir)

please help me to solve this.Thank you请帮我解决这个问题。谢谢

You are declaring a list here mydir = []你在这里声明一个列表mydir = []

Change it to dictionary mydir = {}将其更改为字典mydir = {}

you are doing great with one little mistake.你有一个小错误就做得很好。 you are declaring 'mydir' as a python list and giving it 'p7' as an index.您将 'mydir' 声明为 python 列表,并将它的 'p7' 作为索引。 Python list can't have string indexes. Python 列表不能有字符串索引。 you can change the first line to following.您可以将第一行更改为以下内容。

mydir = {}

You are trying to insert an item into mydir at index 'p7' (which is a string).您正试图在索引'p7' (这是一个字符串)的mydir中插入一个项目。 Indices are integers and not strings .索引是整数而不是字符串 That is why the error.这就是错误的原因。

Your question says that you want to insert into a dictionary and your code uses a list .你的问题说你想插入dictionary ,你的代码使用了一个list

mydir = {} - This is a dictionary mydir = {} - 这是一本字典

mydir = [] - This is a list mydir = [] - 这是一个列表

Here is what you need to do:以下是您需要做的:

mydir = {}
person_trackID = "p7"
class_ids = [3 ,3 ,3 ]
print(mydir,person_trackID,set(class_ids))

mydir[person_trackID] = list(set(class_ids))
print(mydir)
{} p7 {3}
{'p7': [3]}

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

相关问题 列表索引必须是整数或切片而不是 str python - list indices must be integers or slices not str python Python 列表索引必须是整数或切片,而不是 str - Python List indices must be integers or slices, not str 错误列表索引必须是整数或切片,而不是str - error list indices must be integers or slices, not str 列表索引必须是整数或切片,而不是 str 错误 Python - list indices must be integers or slices, not str error Python python json 列表索引必须是整数或切片,而不是 str 错误 - python json list indices must be integers or slices, not str error 在数组中,列表索引必须是整数或切片,而不是 str 错误 python - In an array, list indices must be integers or slices, not str error python Python 字典错误列表索引必须是整数或切片,而不是 str - Python Dictionary error list indices must be integers or slices, not str Python数据相关的错误:列表索引必须是整数或切片,而不是str - Python data related error: list indices must be integers or slices, not str Python 错误:类型错误:列表索引必须是整数或切片,而不是 str - Python Error: TypeError: list indices must be integers or slices, not str Python3-TypeError:列表索引必须是整数或切片,而不是str-List - Python3 - TypeError: list indices must be integers or slices, not str - List
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM