Python - 如果在嵌套列表中找到字符串,则返回 true [英] Python - Return true if strings found in nested list

查看:53
本文介绍了Python - 如果在嵌套列表中找到字符串,则返回 true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我能够检测到嵌套列表中的两个项目,我的目标是返回 True/False.

My goal is to return True/False if I am able to detect two items within a nested list.

例如

list1 = [['1', 'sjndnjd3', 'MSG1'], ['2', 'jdakb2', 'MSG1'], ['1', 'kbadkjh', 'MSG2']]

我想遍历这个列表以确认我是否能找到1"&嵌套列表中的MSG1".重要的是要注意,如果找到两个项目并且在同一个嵌套列表中找到它们,我只希望它返回 true.

I want to iterate over this list to confirm if I can find '1' & 'MSG1' within a nested list. Important to note I only want this to return true if both items are found and if they're found within the same nested list.

我尝试了下面的各种组合,但我不能完全正确.

I've tried various combinations of the below however I cannot get it quite right.

all(x in e for e in list1 for x in ['1', 'MSG1'])

非常感谢任何帮助.

推荐答案

试试这个:

contains = any([True for sublist in list1 if "1" in sublist and "MSG1" in sublist])

这篇关于Python - 如果在嵌套列表中找到字符串,则返回 true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆