蟒蛇。检查索引是否存在于可能的词典列表中

时间:2018-03-04 12:05:30

标签: python arrays python-3.x list dictionary

我有这个:

list_name = [0, 1, 2, 3]
list_name[0] = {}
list_name[0]['test'] = 'any value'

我想知道列表中的密钥是否存在。通常我用:

if 3 not in list_name:
    print("this doesn't exist")
else:
    print("exists")

以3号为例进行测试是有效的。它说“存在”。如果我检查号码999是否有效,则表示“这不存在”。

问题是它不适用于0.正如您所看到的,列表中的0值具有字典。我需要检查列表中是否存在0(如果它有字典则无关紧要)。怎么做到这一点?使用python3,谢谢。

2 个答案:

答案 0 :(得分:3)

如果列表中存在元素0,则列表的长度必须大于零。所以你可以使用:

if len(list_name) > 0:
    print("0 exists")
else:
    print("0 does not exist")

作为旁注,{}是字典,而不是数组。

答案 1 :(得分:1)

使用try except检查索引是否存在

try:
    if list_name[6]:
        print("exists")

except IndexError:
    print("this doesn't exist")

输出

  

这不存在

相关问题