简体   繁体   English

比较python中的两个列表,其中元素的顺序不同

[英]Compare two lists in python where the elements are in different order

I have multiple lists eg 我有多个清单,例如

list1=[1,4,5]
list2=[4,1,5]
list3=[1,5,4]

two lists are considered same if they have the same elements. 如果两个列表具有相同的元素,则认为它们是相同的。 Also the lists can be nested lists 列表也可以是嵌套列表

list1=[[1,4],5,4]
list2=[5,4,[1,4]]

How do i compare them? 我如何比较它们?

You can flatten your lists then use set to keep the unique elements then compare : 您可以flatten列表,然后使用set保留唯一元素,然后进行比较:

>>> from compiler.ast import flatten
>>> list1=[[1,4],5,4]
>>> list2=[5,4,[1,4]]
>>> set(flatten(list1))==set(flatten(list2))
True

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

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