简体   繁体   English

如何在字符串列表中找到 substring?

[英]How to find a substring in a string list?

I try to find some string in a list, but have problems because of word order.我尝试在列表中查找一些字符串,但由于字序而出现问题。

list = ['a b c d', 'e f g', 'h i j k']
str = 'e g'

I need to find the 2nd item in a list and output it.我需要在列表中找到第二个项目和 output 它。

You can try:你可以试试:

for l in list:
     l_words = l.split(" ")
     if all([x in l_words for x in str.split(" ")]):
         print(l_words)

You can try this你可以试试这个

list = ['a b c d', 'e f g', 'h i j k']
str = list[2].split()
for letter in str:
  print(letter)

This can be achieved by using sets and list comprehension这可以通过使用集合和列表理解来实现

ls = ['a b c d', 'e f g', 'h i j k']
s = 'e g'
print([i for i in ls if len(set(s.replace(" ", "")).intersection(set(i.replace(" ", "")))) == len(s.replace(" ", ""))])

OR或者

ls = ['a b c d', 'e f g', 'h i j k']
s = 'e g'
s_set = set(s.replace(" ", ""))
print([i for i in ls if len(s_set.intersection(set(i.replace(" ", "")))) == len(s_set)])

Output Output

['e f g']

The list comprehension is removing all the items in ls that all the chars from s are not including inside the list item, by that you will get all the ls items that all the s chars are in them.列表理解正在删除ls中所有s中的所有字符都不包括在列表项中的项目,这样您将获得所有s字符都在其中的所有ls项目。

You can use combination of any() and all() to check the presence in one line:您可以使用any()all()的组合来检查一行中的存在

>>> my_list = ['a b c d', 'e f g', 'h i j k']
>>> my_str = 'e g'

>>> any(all(s in sub_list for s in my_str.split()) for sub_list in my_list)
True

Here, above expression will return True / False depending on whether the char in your strings are present inside the list.在这里,上面的表达式将根据字符串中的字符是否存在于列表中而返回True / False

To also get the get that sub-list as return value , you can modify above expression by skipping any() with list comprehension as:获取该子列表作为返回值,您可以通过使用列表理解跳过any()来修改上面的表达式:

>>> [sub_list for sub_list in my_list if all(s in sub_list for s in my_str.split())]
['e f g'] 

It'll return the list of strings containing your chars.它将返回包含您的字符的字符串列表。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM