简体   繁体   中英

How to sort list of lists irrespective of their order?

I'm expecting the output [[-1,-1,2],[-1,0,1]] but the below code outputs [[2, -1], [0, 1, -1]] .Basically i want to remove that duplicate pair

What am I doing wrong?

def sum_1(arr):
    
    list_final=[]
    
    for i in range(0,len(arr)-2):
        
        for j in range(i+1,len(arr)-1):
            for k in range(j+1,len(arr)):
                if arr[i]+arr[j]+arr[k]==0:
                    list_final.append([arr[i],arr[j],arr[k]])
    a={frozenset(x) for x in list_final}
    return [list(i) for i in a]
    
sum_1([-1,0,1,2,-1,-4])

It seems that your core problem is that of removing duplicate lists from a list of lists. One approach is to write a utility function which does so, and then call it in your other function:

from itertools import combinations

def de_dup(lol):
    """removes duplicates from list of lists lol"""
    encountered = set()
    uniques = []
    for x in lol:
        t = tuple(x)
        if t not in encountered:
            uniques.append(x)
            encountered.add(t)
    return uniques
    
def sum_1(arr):
    triples = sorted(sorted(c) for c in combinations(arr,3) if sum(c) == 0)
    return de_dup(triples)

print(sum_1([-1,0,1,2,-1,-4])) #prints [[-1, -1, 2], [-1, 0, 1]]

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