如何检查第二个子列表中是否存在元素?

cre*_*not 0 python for-loop nested generator-expression python-3.x

如果我有这样的列表:

L = [
           ['a', 'b'], 
           ['c', 'f'], 
           ['d', 'e']
       ]
Run Code Online (Sandbox Code Playgroud)

我知道我可以'f'通过any以下方式检查是否包含在任何子列表中:

if any('f' in sublist for sublist in L) # True
Run Code Online (Sandbox Code Playgroud)

但是,我将如何搜索第二个子列表,即列表是否按以下方式初始化:

L = [
           [
               ['a', 'b'], 
               ['c', 'f'], 
               ['d', 'e']
           ], 
           [
               ['z', 'i', 'l'],
               ['k']
           ]
       ]
Run Code Online (Sandbox Code Playgroud)

我尝试将for in这样的表达式链接起来:

if any('f' in second_sublist for second_sublist in sublist for sublist in L)
Run Code Online (Sandbox Code Playgroud)

但是,这会崩溃,因为name 'sublist' is not defined.

jpp*_*jpp 5

首先将您的逻辑写为常规 for循环:

for first_sub in L:
    for second_sub in first_sub:
        if 'f' in second_sub:
            print('Match!')
            break
Run Code Online (Sandbox Code Playgroud)

然后使用for相同顺序的语句重写为生成器表达式:

any('f' in second_sub for first_sub in L for second_sub in first_sub)
Run Code Online (Sandbox Code Playgroud)