简体   繁体   English

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

[英]Checking if any elements in one list are in another

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 if to evaluate to True because 5 is in both lists.在此示例中,我希望if评估为True因为 5 在两个列表中。 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

A more compact way you can do it is to use map and reduce :一种更紧凑的方法是使用mapreduce

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

Even better, the reduce can 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

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 isdisjoint is better than intersection for Python 2.6 and above.我相信使用isdisjoint比 Python 2.6 及更高版本的intersection更好。

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

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

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。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM