[英]List Comprehension for Strings
我有兩個列表,如下所示。 我想找出第一個列表中的字符串是否在第二個列表中的任何字符串中。 出於某種原因,當我嘗試運行它時,我得到一個空列表。
例如:在list5
,字符串'apple'
在list6
的'I ate an apple'
。
list5 = ['apple', 'mango', 'sherbet']
list6 = ['I ate an apple', 'I ate two apples', 'I love mango']
print ([x for i,x in enumerate(list5) if x in list6])
對於整數列表,完全相同的事情可以順利運行。 是否有不同的方式來完成字符串?
list7 = [1, 2, 3, 4, 5]
list8 = [1, 2]
print ([x for i,x in enumerate(list7) if x in list8])
您正在檢查apple
是否在列表中,但您要檢查列表中的任何字符串是否包含apple
list5 = ['apple', 'mango', 'sherbet']
list6 = ['I ate an apple', 'I ate two apples', 'I love mango']
[x for x in list5 if any(x in item for item in list6)]
#['apple', 'mango']
這將創建一個列表列表,其中包含第二個列表中句子的索引,其中包含第一個列表中的單詞
list5 = ['apple', 'mango', 'sherbet']
list6 = ['I ate an apple', 'I ate two apples', 'I love mango', '2 apple', 'big apple', 'big mango']
[[i for i, sentence in enumerate(list6) if x in sentence] for x in list5]
#[[0, 1, 3, 4], [2, 5], []]
正如我在評論中所說,字典在這種情況下會更好
{x:[i for i,sen in enumerate(list6) if x in sen] for x in list5}
#{'apple': [0, 1, 3, 4], 'mango': [2, 5], 'sherbet': []}
如果只存儲完全匹配,你可以使用它,但如果第一個列表不僅包含單詞,這不起作用,例如,如果list5
包含“一個蘋果”這不起作用
{x:[i for i,sen in enumerate(list6) if any(x==item for item in sen.split())] for x in list5}
#{'apple': [0, 3, 4], 'mango': [2, 5], 'sherbet': []}
你的代碼正在檢查x
是否是list6
的成員,當你想知道x
是否是list6
中任何成員的子字符串時。 你可以使用Python的reduce
方法(在Python 3的functools
)這樣做。
list5 = ['apple', 'mango', 'sherbet']
list6 = ['I ate an apple', 'I ate two apples', 'I love mango']
from functools import reduce
print([x for x in list5
if reduce(lambda exist, s: exist or (x in s), list6, False)])
# ['apple', 'mango']
reduce
調用迭代遍歷list6
所有成員並檢查x
是否是子字符串,然后或者將這些結果反對exist
(這里默認為False
),如果至少找到一次則返回True
。 請參閱functools.reduce的Python3文檔,以便更好地了解它的工作原理。
聽起來你要求設置交集,在這種情況下我會繞過並使用集合代替列表並使用交集運算符而不是循環,就像這樣a & b
,其中a和b是集合。
但是你的例子讓你看起來像是在list6中的每個字符串中查找list5中的子字符串,這可能是完全不同的,我們需要更多關於你的預期輸出可以幫助你更多的信息。
同樣順便說一下,你不需要使用枚舉,因為你沒有使用它的值。
#!python3
import re
list5 = ['apple', 'mango', 'sherbet']
list6 = ['I ate an apple', 'I ate two apples', 'I love mango']
for item in list6:
for substr in list5:
if re.search(r"\b" + re.escape(substr) + r"\b", item):
print('"' + substr + '"' + ' is in ' + '"' + item + '"')
'''
# output
"apple" is in "I ate an apple"
"mango" is in "I love mango"
'''
list7 = [1, 2, 3, 4,5]
list8 = [1,2]
for substr in list8:
if substr in list7:
print(substr, 'is in', list7)
'''
# output
1 is in [1, 2, 3, 4, 5]
2 is in [1, 2, 3, 4, 5]
'''
一種方法是在列表理解中調用函數。
它不是單線,但邏輯清晰,一旦找到匹配就會短路。
list5 = ['apple', 'mango', 'sherbet']
list6 = ['I ate an apple', 'I ate two apples', 'I love mango']
def find_word(x, sentences):
for item in sentences:
if x in item:
return x
res = [x for x in list5 if find_word(x, list6)]
# ['apple', 'mango']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.