Python 检查一个列表中的任何元素是否在另一个列表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16138015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:50:59  来源:igfitidea点击:

Checking if any elements in one list are in another

pythonlist

提问by h1h1

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")

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

在此示例中,我希望if计算为True5 ,因为 5 在两个列表中。这不起作用,我不确定比较两个列表的最简单方法。

采纳答案by David Alber

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

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

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

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

Even better, the reducecan be replaced with any:

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

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

You could also use sets:

您还可以使用集合:

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

回答by vidit

There are different ways. If you just want to check if one list contains any element from the other list, you can do this..

有不同的方法。如果您只想检查一个列表是否包含另一个列表中的任何元素,您可以这样做..

not set(list1).isdisjoint(list2)

I believe using isdisjointis better than intersectionfor Python 2.6 and above.

我相信使用isdisjointintersectionPython 2.6 及更高版本更好。

回答by dansalmo

Your original approach can work with a list comprehension:

您的原始方法可以与列表理解一起使用:

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

回答by user1463110

There is a built in function to compare lists:

有一个内置函数来比较列表:

Following is the syntax for cmp() method ?

以下是 cmp() 方法的语法?

cmp(list1, list2)

#!/usr/bin/python

list1, list2 = [123, 'xyz'], [123, 'xyz']

print cmp(list1,list2)

When we run above program, it produces following result ?

当我们运行上面的程序时,它会产生以下结果?

0

If the result is a tie, meaning that 0 is returned

如果结果是平局,则意味着返回 0

回答by colins44

You could change the lists to sets and then compare both sets using the & function. eg:

您可以将列表更改为集合,然后使用 & 函数比较两个集合。例如:

list1 = [1, 2, 3, 4, 5]
list2 = [5, 6, 7, 8, 9]

if set(list1) & set(list2):
    print "Number was found"
else:
    print "Number not in list"

The "&" operator gives the intersection point between the two sets. If there is an intersection, a set with the intersecting points will be returned. If there is no intersecting points then an empty set will be returned.

“&”运算符给出两个集合之间的交点。如果存在交点,则返回具有交点的集合。如果没有相交点,则将返回一个空集。

When you evaluate an empty set/list/dict/tuple with the "if" operator in Python the boolean False is returned.

当您在 Python 中使用“if”运算符评估空集/列表/字典/元组时,将返回布尔值 False。

回答by Aman Madan

I wrote the following code in one of my projects. It basically compares each individual element of the list. Feel free to use it, if it works for your requirement.

我在我的一个项目中编写了以下代码。它基本上比较列表中的每个单独元素。如果它适合您的要求,请随意使用它。

def reachedGoal(a,b):
    if(len(a)!=len(b)):
        raise ValueError("Wrong lists provided")

    for val1 in range(0,len(a)):
        temp1=a[val1]
        temp2=b[val1]
        for val2 in range(0,len(b)):
            if(temp1[val2]!=temp2[val2]):
                return False
    return True