[英]Search a string using list elements for matches and return the match found
[英]Search list of string elements that match another list of string elements
我有一个名为names
字符串列表,我需要使用pattern
列表中的每个元素搜索names
列表中的每个元素。 找到了几个可以循环访问单个字符串但不是字符串列表的指南
a = [x for x in names if 'st' in x]
先感谢您!
names = ['chris', 'christopher', 'bob', 'bobby', 'kristina']
pattern = ['st', 'bb']
期望的输出:
a = ['christopher', 'bobby', 'kristina]
将any()函数与生成器表达式一起使用 :
a = [x for x in names if any(pat in x for pat in pattern)]
any()
是一个短路函数,因此第一次遇到匹配的模式时,它返回True。 由于我使用的是生成器表达式而不是列表推导,因此甚至不会检查匹配的第一个模式之后的模式。 这意味着这只是最快的方式。
你可以这样做:
[name for name in names if any([p in name for p in pattern])]
代码是自我解释的,只是大声朗读; 我们正在创建一个包含其中一个模式的所有名称的列表。
使用两个循环:
for name in names:
for pattern in patterns:
if pattern in name:
# append to result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.