简体   繁体   English

我如何比较python中的两个列表,并返回第二个需要具有相同值而不管顺序?

[英]How can I compare two lists in python, and return that the second need to have the same values regardless of order?

a = [1, 2, 3, 4]
b = [2, 4, 3, 1]
c = [2, 3]

When comparing a to b, should return True : all items in a are presented in b , and all items in b are presented in a . 当比较A到B,应该返回True :在所有项目a都在呈现b ,并在所有项目b都在呈现a

When comparing a to c , should return False : there are items in a that don't exist on c . 当比较ac ,应该返回False :有在项目a不上存在c

What is the pythonic way to do it? 什么是pythonic方式呢?

排序,然后比较。

sorted(a) == sorted(b)

Use sets or frozensets. 使用集合或frozensets。

set_a = {1, 2, 3, 4} #python 2.7 or higher set literal, use the set(iter) syntax for older versions
set_b = {2, 4, 4, 1}

set_a == set_b

set_a - set_b == set_b - set_a

The biggest advantage of using sets over any list method is that it's highly readable, you haven't mutated your original iterable, it can perform well even in cases where a is huge and b is tiny (checking whether a and b have the same length first is a good optimization if you expect this case often, though), and using the right data structure for the job is pythonic. 使用集合优于任何列表方法的最大优点是它具有高可读性,您没有改变原始可迭代,即使在a很大且b很小的情况下它也可以很好地执行(检查a和b是否具有相同的长度)首先是一个很好的优化,如果你经常期望这种情况,并且使用正确的数据结构是pythonic。

Use set s: 使用set s:

In [4]: set(a) == set(b)
Out[4]: True

In [5]: set(a) == set(c)
Out[5]: False

Turn them into sets: 把它们变成几组:

>>> set([1,2,3,4]) == set([2,4,3,1])
True

>>> set([2, 3]) == set([1,2,3,4])
False

If your lists contain duplicate items, you'll have to compare their lengths too. 如果您的列表包含重复项,则您还必须比较它们的长度。 Sets collapse duplicates. 设置折叠重复项。

暂无
暂无

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

相关问题 如何在python中根据相同顺序比较两个列表中的单词?(我有一个def函数) - How to compare words in two lists according to same order in python?(I have def a function) 如何将4位数字变量与4位数字列表进行比较,并确定它们是否具有完全相同的数字,而不管顺序如何? - How Can I Compare A 4 Digit Variable To A List Of 4 Digit Numbers And Determine If They Have The Exact Same Numbers, Regardless Of Order? 如何比较两个Django QuerySet并返回QuerySet并从第二个开始先替换相同的值? - How can I compare two Django QuerySets and return QuerySet with replacement of the same values from second in first? 如何比较python中的两个列表并通过电子邮件返回匹配项 - How can I compare two lists in python and return matches by email 如何比较python中的两个列表并返回匹配项 - How can I compare two lists in python and return matches 如何比较python中的两个列表并返回不匹配 - How can I compare two lists in python and return not matches 如何比较python中两个列表的值? - How can I compare the values of two lists in python? python:比较两个列表并按顺序返回匹配项 - python: compare two lists and return matches in order 如何比较 Python 中的两个列表列表并找到匹配值 - How can I compare two lists of lists in Python and find matching values 如何比较两个列表的三元词组合并在 Python 中返回相同的组合? - How do I compare Trigram-word-combinations of two lists and return same combinations in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM