[英]Python. Check if index exists in a list of possible dictionaries
I have this: 我有这个:
list_name = [0, 1, 2, 3]
list_name[0] = {}
list_name[0]['test'] = 'any value'
I want to know if a key of the list exists or not. 我想知道列表中的键是否存在。 Usually I use: 通常我使用:
if 3 not in list_name:
print("this doesn't exist")
else:
print("exists")
And testing this for example for number 3 is working. 例如,对3号进行测试就可以了。 It says "exists". 它说“存在”。 If I check for number 999 is working, it says "this doesn't exist". 如果我检查数字999是否正常工作,则显示“此地址不存在”。
The problem is that it is not working for 0. As you can see, 0 value in the list has a dictionary. 问题在于它不适用于0。如您所见,列表中的0值具有字典。 And I need to check if 0 exists or not in the list (doesn't matter if it has a dictionary or not). 而且我需要检查列表中是否存在0(无论是否具有字典都没有关系)。 How to achieve this? 如何实现呢? Using python3, thank you. 使用python3,谢谢。
If element 0
exists in the list, then the length of the list must be greater than zero. 如果列表中存在元素0
,则列表的长度必须大于零。 So you could use: 因此,您可以使用:
if len(list_name) > 0:
print("0 exists")
else:
print("0 does not exist")
As a side note, {}
is a dictionary, not an array. 另外, {}
是字典,而不是数组。
Use try
except
for check index is exists or not 使用try
except
检查索引是否存在
try:
if list_name[6]:
print("exists")
except IndexError:
print("this doesn't exist")
Output 输出量
this doesn't exist 这个不存在
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.