search_terms = ['word','cow','horse']
library = [['desk','chair','lamp'],['cow','horse','word 223','barn']]
我希望能够在库中打印包含search_terms中所有术语的所有列表。
所以使用上面的search_terms列表会在库中打印第二个子列表,即使'word 223'只包含'word',但不是直接匹配。
我不会总是拥有相同数量的字符串...
感谢任何愿意帮助我的人!
感谢falsetru帮助我解决第一个问题!
答案 0 :(得分:3)
要获得点击量,请使用列表理解:
search_terms = ['word', 'cow', 'horse']
library = [['desk', 'chair', 'lamp'],
['cow', 'horse', 'word 223', 'barn']]
hits = [l for l in library if
all(any(t in s for s in l)
for t in search_terms)]
这可以如下工作
for
l
; library
{li> for
all
条t
search_terms
;
{li> if
any
s
中l
的{{1}}包含它;
l
保留在新列表hits
中。 答案 1 :(得分:0)
>>> search_terms = ['word','cow','horse']
>>> library = [['desk','chair','lamp'],['cow','horse','word 223','barn']]
>>> from itertools import chain
>>> list(chain(*library))
['desk', 'chair', 'lamp', 'cow', 'horse', 'word 223', 'barn']
>>> [word for word in search_terms if word in list(chain(*library))]
['cow', 'horse']
>>> [l for l in library if any(word for word in search_terms if word in l)]
[['cow', 'horse', 'word 223', 'barn']]