简体   繁体   中英

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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