使用列表项的 "existence" 作为条件 Python 的 if 语句

Using the "existence" of a list item as an if-statement conditional with Python

我在 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

它应该是一个备份:如果我没有得到两个列表的值,我只想使用第一个列表中的值。然后,如果我没有第一个列表中的项目,我将使用第二个列表。所以我要问的是:如何测试列表中的项目 'EXISTS'?

检查列表的长度。

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

在布尔上下文中评估列表会检查列表是否非空。

如果要检查 list[n] 是否存在,请使用 if len(list) > n。列表索引总是连续的,从不跳过,所以它有效。

如果你想检查特定索引的元素是否在列表中,你可以检查index < len(list1)。 (假设索引是一个非负整数)

if index < len(list1) and index < len(list2):
    #do something using both lists
elif index < len(list1):
    #do something using just the first list
elif index < len(list2):
    #do something using just the second list

如果您想检查特定值的元素是否在列表中,您将使用 if value in list1

if value in list1 and value in list2:
    #do something using both lists
elif value in list1:
    #do something using just the first list
elif value in list2:
    #do something using just the second list