检查一个列表中的任何元素是否在另一个列表中 [英] Checking if any elements in one list are in another

查看:58
本文介绍了检查一个列表中的任何元素是否在另一个列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试比较两个列表,如果第二个列表中有第一个列表中的任何值,则只打印一条消息.

I'm trying to compare two lists and simply print a message if any value from the first list is in the second list.

def listCompare():
  list1 = [1, 2, 3, 4, 5]
  list2 = [5, 6, 7, 8, 9]
  if list1 in list2:
    print("Number was found")
  else:
    print("Number not in list")

在此示例中,我希望if的值为True,因为两个列表中均包含5.这行不通,而且我不确定比较这两个列表的最简单方法.

In this example, I want the if to evaluate to True because 5 is in both lists. This doesn't work, and I'm not sure of the simplest way to compare the two lists.

推荐答案

您可以解决许多问题.一个很容易理解的方法就是使用循环.

You could solve this many ways. One that is pretty simple to understand is to just use a loop.

def comp(list1, list2):
    for val in list1:
        if val in list2:
            return True
    return False

一种更紧凑的方法是使用 map reduce :

A more compact way you can do it is to use map and reduce:

reduce(lambda v1,v2: v1 or v2, map(lambda v: v in list2, list1))

更好的是,可以将reduce替换为 any :

Even better, the reduce can be replaced with any:

any(map(lambda v: v in list2, list1))

您还可以使用集合:

len(set(list1).intersection(list2)) > 0

这篇关于检查一个列表中的任何元素是否在另一个列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆