簡體   English   中英

Python - 如果在嵌套列表中找到字符串,則返回 true

[英]Python - Return true if strings found in nested list

如果我能夠檢測到嵌套列表中的兩個項目,我的目標是返回 True/False。

例如

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

我想遍歷此列表以確認是否可以在嵌套列表中找到“1”和“MSG1”。 重要的是要注意,如果找到兩個項目並且在同一個嵌套列表中找到它們,我只希望它返回 true。

我已經嘗試了下面的各種組合,但我不能完全正確。

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])

您可以使用set.issubset

any(True for sub_list in list1 if {'1', 'MSG1'}.issubset(set(sub_list)))

您需要將all應用於list11MSG每個測試,因此您需要將列表理解重寫為

found = [all(x in e for x in ['1', 'MSG1']) for e in list1]
# [True, False, False]

然后,您可以測試這些值中的任何一個是否為真:

any(found)
# True

您可以使用sum和 list 的count方法創建如下函數:

def str_in_nested(list_, string_1, string_2):
    return sum(sub_list.count(string_1) and sub_list.count(string_2) for sub_list in list_) > 0

將此功能應用於您當前的案例:

>>> list1 = [['1', 'sjndnjd3', 'MSG1'], ['2', 'jdakb2', 'MSG1'], ['1', 'kbadkjh', 'MSG2']]
>>> str_in_nested(list1, '1', 'MSG1')
True

它的:

any(all(item in sublist for item in ['1', 'MSG1']) for sublist in list1)

試試這個...

for item in list1:
    all(i in item for i in sub)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM