You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何判断字符串是否存在于嵌套列表的任意元素中

Python二层嵌套列表成员存在性判断方法

场景1:外层列表仅包含1个多元素子列表

你给出的第一个示例属于二层嵌套结构,外层列表仅有1个存储所有名称的子列表,有两种常用实现方式:

通用适配写法(兼容所有二层嵌套结构)

使用内置函数any()遍历所有子列表判断,只要任意子列表包含目标元素就返回True:

Name_list = [
    ['Name 1', 'Name 2', 'Name 3']
]
Name = 'Name 3'

if any(Name in sublist for sublist in Name_list):
    print('Name is in the list')

简化写法(仅适配当前固定结构)

如果确定外层列表永远只有1个子列表,可以直接取第一个子列表做成员判断:

if Name in Name_list[0]:
    print('Name is in the list')

场景2:外层列表每个子元素均为单元素列表

上面提到的any()通用写法不需要做任何修改,直接复用即可。如果想简化判断,也可以先把嵌套列表摊平为一维列表再判断:

list_1 = [
    ['Name 1'],
    ['Name 2'],
    ['Name 3']
]
Name = 'Name 3'

# 写法1:通用写法直接复用
if any(Name in sublist for sublist in list_1):
    print('Name is in the list')

# 写法2:先摊平再判断
flatten_list = [item[0] for item in list_1]
if Name in flatten_list:
    print('Name is in the list')

补充说明

如果你的嵌套列表层级超过2层,可以写递归函数实现全局成员判断,当前2层嵌套场景下any()写法已经可以覆盖所有情况,适配性最高。

内容的提问来源于stack exchange,提问作者Eskimo868

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 21:48:01