[英]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 dictionarymydir = {}
- 这是一本字典
mydir = []
- This is a listmydir = []
- 这是一个列表
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.