【问题标题】:move to next item in list1 when item from list2 is found, when both lists are compared当找到 list2 中的项目时,移动到 list1 中的下一个项目,同时比较两个列表
【发布时间】:2018-12-24 10:45:05
【问题描述】:

对不起,标题太复杂了,也许例子会更容易。

所以我有两个列表:

list1 = ['cat', 'dog', 'donkey']
list2 = ['http://cat1.com', 'http://cat2.com', 'http://dog1.com', http://dog2.com']

我想要的只是脚本,用 list1 项目“greps”list2 但是当它找到一个 ocurence 时,它​​会移动到 list1 中的另一个项目,所以它会在“@987654321”中找到短语“cat” @",然后它检查 list[1] item: 'dog'。完成后,它应该打印所有的发现。 我尝试使用 .find() 但它不适用于列表类型的文件。

【问题讨论】:

    标签: python list if-statement find


    【解决方案1】:

    你可以试试这个:

    list1 = ['cat', 'dog', 'donkey']
    list2 = ['http://cat1.com', 'http://cat2.com', 'http://dog1.com', 'http://dog2.com']
    
    for item in list1:
        for url in list2:
            if item in url:
                print url
                break
    

    输出:

    http://cat1.com
    http://dog1.com
    

    更高级的方法可能是:

    urls = filter(lambda x: x in list2, list1)
    print urls
    

    【讨论】:

    • 完美,非常感谢,这正是我要求的!
    【解决方案2】:

    也许你可以这样做:

    list1 = ['cat', 'dog', 'donkey']
    list2 = ['http://cat1.com', 'http://cat2.com', 'http://dog1.com', 'http://dog2.com']
    
    for animal in list1:
         for site in list2:
                 if animal in site:
                         print(f'{animal} : {site}')
                         break                     
    

    输出:

    cat : http://cat1.com
    dog : http://dog1.com
    

    【讨论】:

      【解决方案3】:
      list1 = ['cat', 'dog', 'donkey']
      list2 = ['http://cat1.com', 'http://cat2.com', 'http://dog1.com', 'http://dog2.com']
      output = [l2 for l2 in list2 for l1 in list1 if l1 in l2]
      print(output)
      

      您的 list2 中的最后一项也缺少撇号。

      【讨论】:

        猜你喜欢
        • 2020-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多