我在 Python3 中有一个程序,我在其中获取值并将它们附加到两个列表中的一个(我将某些值排序到某个列表中)。然后我想做这样的事情(只是使用列表中第一项的示例):
if list1[0] and list2[0] exist:
#do something using both lists
else:
if list1[0] exists:
#do something using just the first list
else:
#do something using just the second list
它应该是一个备份:如果我没有得到两个列表的值,我只想使用第一个列表中的值。然后,如果我没有第一个列表中的项目,我将使用第二个列表。所以我要问的是:如何测试列表中的项目是否“存在”?
请您参考如下方法:
检查列表的长度。
if len(list1) > 0 and len(list2) > 0:
# do something using both lists
elif len(list1) > 0:
# do something using just the first list
else:
# do something using just the second list
如果您专门寻找第一个元素,可以将其缩短为:
if list1 and list2:
# do something using both lists
elif list1:
# do something using just the first list
else:
# do something using just the second list
在 bool 上下文中评估列表会检查列表是否为非空。
