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

问题描述 投票:1回答:2

我有这个:

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,谢谢。

python arrays python-3.x list dictionary
2个回答
1
投票

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

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

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

产量

这不存在


3
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.