简体   繁体   English

如何提取嵌套列表中包含的字符串?

[英]How to extract a string contained in nested list?

Please help me out to extract the string containing particular text.请帮我提取包含特定文本的字符串。 I have tried with below:我尝试过以下方法:

lst = [['abc', 'abgoodhj', 'rygbadkk'], ['jhjbadnm'], ['hjhj', 'iioytu'], ['hjjh', 'ghjgood1hj', 'jjkkbadgghhj', 'hjhgkll']]

for lst1 in lst:
    good_wrd = [txt for txt in lst1 if txt.contains('good')]
    bad_wrd = [txt for txt in lst1 if txt.contains('bad')]

I want the words that contain good and bad .我想要包含goodbad的单词。

use list comprehension to create a new list.使用列表推导来创建一个新列表。

good_wrd = [
    word
    for sub_lst in lst
    for word in sub_lst
    if "good" in word
]
bad_wrd = [
    word
    for sub_lst in lst
    for word in sub_lst
    if "bad" in word
]

Alternatively using for loops:或者使用 for 循环:

good_wrd = []
bad_wrd = []

for sub_lst in lst:
    for word in sub_lst:
        if "bad" in word:
            bad_wrd.append(word)
        elif "good" in word:
            good_wrd.append(word)

This would work:这会起作用:

lst = [['abc', 'abgoodhj', 'rygbadkk'], ['jhjbadnm'], ['hjhj', 'iioytu'], ['hjjh', 'ghjgood1hj', 'jjkkbadgghhj', 'hjhgkll']]

good_wrd = []
bad_wrd = []
for lst1 in lst:
    good_wrd.extend([txt for txt in lst1 if 'good' in txt])
    bad_wrd.extend([txt for txt in lst1 if 'bad' in txt])

print(good_wrd)
print(bad_wrd)
target1 = 'good'
target2 = 'bad'
goods = []
bads = []
for lis in lst:
    for txt in lis:
        if target1 in txt:
            goods.append(txt)
        elif target2 in txt:
            bads.append(txt)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何匹配包含在四个列表中的子字符串? - How match contained sub string in four list? 如何测试字符串是否部分包含在 Python 的列表中 - How to test if a string is partialy contained in a list in Python 将字符串中的元素提取到嵌套列表中 - Extract element within string into nested list 如何提取嵌套列表的第n个元素的第一个元素(作为字符串列表) - How to extract the first element (as a list of string) of the n-th elements of a nested list, Python 如何检查列表中的部分字符串是否包含在 Python 的另一个列表中 - How to check if part of a string in a list is contained in another list in Python 如何删除包含在同一字符串列表中的其他字符串中的字符串? - How can I drop strings contained in other string contained in the same string list? 如何从列表中提取字符串 - How to extract a string from a list 如何从python 3中的嵌套列表中提取日期和第一次出现数字之间的字符串? - How to extract string between date and first occurrence of digit from nested list in python 3? 如何在python中提取嵌套的json名称并转换为点符号字符串列表? - How do I extract nested json names and convert to dot notation string list in python? 如何检查列表中的哪些单词包含在字符串中? - How to check which words from a list are contained in a string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM