如何打印包含另一个列表中所有字符串的子列表?

时间:2014-01-01 07:17:33

标签: python

search_terms = ['word','word 1','word 2']

library = [['desk','chair','lamp'],['cow','word','horse','word 2','word 1']]

我只是希望能够在库中打印包含search_terms中所有术语的所有列表。列表search_terms并不总是具有相同数量的字符串......

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

1 个答案:

答案 0 :(得分:6)

使用set.issubset

>>> {'word','word 1','word 2'}.issubset(['desk','chair','lamp'])
False
>>> {'word','word 1','word 2'}.issubset(['cow','word','horse','word 2','word 1'])
True

>>> search_terms = ['word','word 1','word 2']
>>> library = [['desk','chair','lamp'],['cow','word','horse','word 2','word 1']]
>>> terms = set(search_terms)
>>> [x for x in library if terms.issubset(x)]
[['cow', 'word', 'horse', 'word 2', 'word 1']]