简体   繁体   English

通过在 python 中传递字符串从列表中查找匹配的单词

[英]Find matching words from a list by passing string in python

I have a list with names, I am trying to search list by passing a string, as output I need all the names from the list that matches to the word.我有一个包含名称的列表,我试图通过传递一个字符串来搜索列表,因为 output 我需要列表中与该单词匹配的所有名称。

EX:前任:

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'HiHello', 'Hellotent', 'Tenthello']
sub = "Hello"

matches = [match for match in ls if sub in match]

print(matches)

['Hello from AskPython', 'Hello', 'Hello boy!', 'HiHello', 'Hellotent', 'Tenthello']

But Expected output is:但预期的 output 是:

['Hello from AskPython', 'Hello', 'Hello boy!']

In the above example "Hello" appeared in between name, I need to exclude such words.在上面的例子中“你好”出现在名字之间,我需要排除这些词。

You can use regular expression or split the string and use any() to check if the sub is present:您可以使用正则表达式或拆分字符串并使用any()检查sub是否存在:

matches = [s for s in ls if any(sub == word for word in s.split())]
print(matches)

Prints:印刷:

['Hello from AskPython', 'Hello', 'Hello boy!']

Here is how you can achieve this : instead of checking if sub is in match you can split(by empty space) the match string and only check if the first element of the split is equal to sub or not.以下是实现此目的的方法:您可以拆分(通过空格)匹配字符串,而不是检查 sub 是否匹配,并且只检查拆分的第一个元素是否等于 sub。

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'HiHello', 'Hellotent', 
     'Tenthello']
sub = "Hello"

matches = [match for match in ls if match.split()[0] == sub]

print(matches)

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

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