繁体   English   中英

如何相互检查两个列表?

[英]How to check two lists against each other?

如果我有两个列表,我希望能够看到一个列表中的项目是否与另一个列表进行比较。 例如,如果我有list1=[1,2,3]list2=[2,3,5,1]我希望能够看到列表2中的数字是否与列表1匹配,而它们的顺序和顺序不同即使还有其他数字。 当你有两组数字并且必须得到它们的交集时,有点像数学。 有没有办法看看list2是否包含list1中的所有项目而不管订单或其他数字? 我正在使用它来执行if命令,根据列表是否与其他列表等效,然后将变量更改为“true”来检测某些内容是否为真。

这是一个类似于我试图开始工作的代码的例子。

listOne=[]
listRight=[1,2,5]

right="false"
while(win != "true"):

  option=input("What number would you like to add to list one?")
    if(option=="1"):
        listOne.append(1)
    elif(option=="2"):
        listOne.append(2)

  if(listOne==listRight):
    right="true"

谢谢您的帮助。

注意:我的列表中不会有任何重复项。 一个将是3个数字的列表,即[1,4,7],另一个列表将是从0到9的任何数字,仅使用数字1-9。 我希望能够检查所有3个数字是否在第二个列表中的任何位置,无论是否有额外的数字。 就像是[1,5,9]是第一个列表而[7,1,3,6,9,5]是第二个列表一样,它们会回归真实,它们彼此相等。

是的, 使用套装

>>> list1=[1,2,3]
>>> list2=[2,3,5,1]
>>> set(list1) & set(list2) # intersection
{1, 2, 3}
>>> set(list1) | set(list2) # union
{1, 2, 3, 5}
>>> set(list1) - set(list2) # set difference
set()
>>> set(list2) - set(list1) # set difference
{5}
>>> set(list1) ^ set(list2) # symmetric difference
{5}
>>>

和子集关系:

>>> set(list1) < set(list1) # proper subset with <
False
>>> set(list1) < set(list1)
False
>>> set(list1) < set(list2)
True
>>> set(list1) <= set(list1) # normal subset
True
>>>

Python有一个set类型,您可以使用a <= b (或不太可读的b.issubset(a) )来检查a是否是b的子集。

一些例子( {a, b, c}set([a, b, c]) )的简写:

>>> {1, 2} <= {1, 2, 3}
True

>>> {2, 1, 5} <= {1, 5, 2}
True

>>> set() <= {0}
True

>>> {1, 2, 4} <= {1, 2, 5}
False

在您的代码中使用:

attempt = set()
right = {1, 2, 5}

while not right <= attempt:
    option = input("What number would you like to add to list one?")
    attempt.add(int(option))

当你说要查看两个列表中的数字是否匹配时,你究竟是什么意思? 假设list1 = [1, 1]list2 = [1, 1, 1] ,在这种情况下你期望返回值为True吗? 如果是,或者你不在乎,那么简单地使用套装就是你的答案。

list1 = [1, 2, 3]
list2 = [1, 3, 3, 3, 2]
list3 = [3, 2]
print(set(list1) == set(list2)) # => True
print(set(list1) == set(list3)) # => False

我猜你在你的应用程序中,你不希望遇到重复,所以这应该是可以接受的。 但是,如果您确实希望重复希望保留它们, 那么您可能想要从头开始构建一个方法,您可以对列表进行排序(第一次)。

暂无
暂无

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

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