![](/img/trans.png)
[英]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.