简体   繁体   English

搜索与另一个字符串元素列表匹配的字符串元素列表

[英]Search list of string elements that match another list of string elements

I have a list with strings called names , I need to search each element in the names list with each element from the pattern list. 我有一个名为names字符串列表,我需要使用pattern列表中的每个元素搜索names列表中的每个元素。 Found several guides that can loop through for a individual string but not for a list of strings 找到了几个可以循环访问单个字符串但不是字符串列表的指南

a = [x for x in names if 'st' in x]

Thank you in advance! 先感谢您!

names = ['chris', 'christopher', 'bob', 'bobby', 'kristina']
pattern = ['st', 'bb']

Desired output: 期望的输出:

a = ['christopher', 'bobby', 'kristina]

Use the any() function with a generator expression : any()函数与生成器表达式一起使用

a = [x for x in names if any(pat in x for pat in pattern)]

any() is a short-circuiting function, so the first time it comes across a pattern that matches, it returns True. any()是一个短路函数,因此第一次遇到匹配的模式时,它返回True。 Since I am using a generator expression instead of a list comprehension, no patterns after the first pattern that matches are even checked. 由于我使用的是生成器表达式而不是列表推导,因此甚至不会检查匹配的第一个模式之后的模式。 That means that this is just about the fastest possible way of doing it. 这意味着这只是最快的方式。

You can do something like this: 你可以这样做:

[name for name in names if any([p in name for p in pattern])]

The code is self explanatory, just read it out loud; 代码是自我解释的,只是大声朗读; we're creating a list of all names that have one of the patterns in them. 我们正在创建一个包含其中一个模式的所有名称的列表。

Using two loops: 使用两个循环:

for name in names:
    for pattern in patterns:
        if pattern in name:
            # append to result

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

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