Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/google-app-engine/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 打印包含其他列表中所有字符串的子列表,而不一定是直接匹配_Python - Fatal编程技术网

Python 打印包含其他列表中所有字符串的子列表,而不一定是直接匹配

Python 打印包含其他列表中所有字符串的子列表,而不一定是直接匹配,python,Python,我希望能够打印库中包含搜索词中所有词的所有列表 因此,使用上面的搜索词列表将打印库中的第二个子列表,即使“word 223”只包含“word”,但不是直接匹配 我不会总是有相同数量的字符串 谢谢所有愿意帮助我的人 感谢falsetru帮我回答第一个问题 要获得您的点击率,请使用列表: search_terms = ['word','cow','horse'] library = [['desk','chair','lamp'],['cow','horse','word 223','barn']

我希望能够打印库中包含搜索词中所有词的所有列表

因此,使用上面的搜索词列表将打印库中的第二个子列表,即使“word 223”只包含“word”,但不是直接匹配

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

谢谢所有愿意帮助我的人


感谢falsetru帮我回答第一个问题

要获得您的点击率,请使用列表:

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

library = [['desk','chair','lamp'],['cow','horse','word 223','barn']]
其工作原理如下

  • 用于
    库中的每个子列表
    l
  • 搜索
    中的所有
    术语
    t
  • 如果
    l
    中的
    s
    字符串中的任何
    包含它
    
  • l
    保留在新列表中
    hits

    他想打印每个子列表,而不是找到的搜索词列表。输出应该是
    ['cow'、'horse'、'word223'、'barn']
    。。。令人困惑的问题=)@alvas对此表示抱歉。现在你知道我的意图了,请随意编辑,让我更清楚。谢谢你的帮助。我通常不喜欢这种复杂的列表理解,但这是一个很好的答案。它似乎没有返回任何结果。它只返回一个空列表。@Alva不,不是,我的comp将库中的列表与额外项目进行匹配,并且根据OPs,术语仅是项目的一部分requirements@jonrsharpe就这样!我仍然不太明白它是如何工作的,lol,但我会继续看它,我会阅读关于列表理解的内容。非常感谢你!以后试着展示一些代码-人们通常不愿意为你写答案。:)@henrebotha我脑子里没有这个问题的可能解决方案,因为我2天前才开始使用python。除了我提供的列表之外,我没有任何相关代码可以显示。
    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)]
    
    >>> 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']]