打印包含另一个列表中所有字符串的子列表,而不必是直接匹配

时间:2014-01-01 14:24:16

标签: python

search_terms = ['word','cow','horse']

library = [['desk','chair','lamp'],['cow','horse','word 223','barn']]

我希望能够在库中打印包含search_terms中所有术语的所有列表。

所以使用上面的search_terms列表会在库中打印第二个子列表,即使'word 223'只包含'word',但不是直接匹配。

我不会总是拥有相同数量的字符串...

感谢任何愿意帮助我的人!

感谢falsetru帮助我解决第一个问题!

2 个答案:

答案 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)]

这可以如下工作

  1. for l;
  2. 中的每个子列表library {li> for allt search_terms; {li> if any sl的{​​{1}}包含它;
  3. 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']]