Get unique elements from a 2D list

后端 未结 1 1154
别跟我提以往
别跟我提以往 2021-01-27 07:26

I have a 2D list which I create like so:

Z1 = [[0 for x in range(3)] for y in range(4)]

I then proceed to populate this list, such that Z1

相关标签:
1条回答
  • 2021-01-27 07:53

    If the order of the elements inside the sublists does not matter, you could use the following:

    from collections import Counter
    
    z1 = [[1, 2, 3], [4, 5, 6], [2, 3, 1], [2, 5, 1]]
    
    temp = Counter([tuple(sorted(x)) for x in z1])
    
    z2 = [list(k) for k, v in temp.items() if v == 1]
    print(z2)  # [[4, 5, 6], [1, 2, 5]]
    

    Some remarks:

    • sorting makes lists [1, 2, 3] and [2, 3, 1] from the example equal so they get grouped by the Counter
    • casting to tuple converts the lists to something that is hashable and can therefore be used as a dictionary key.
    • the Counter creates a dict with the tuples created above as keys and a value equal to the number of times they appear in the original list
    • the final list-comprehension takes all those keys from the Counter dictionary that have a count of 1.

    If the order does matter you can use the following instead:

    z1 = [[1, 2, 3], [4, 5, 6], [2, 3, 1], [2, 5, 1]]
    
    def test(sublist, list_):
        for sub in list_:
            if all(x in sub for x in sublist):
                return False
        return True
    
    z2 = [x for i, x in enumerate(z1) if test(x, z1[:i] + z1[i+1:])]
    print(z2)  # [[4, 5, 6], [2, 5, 1]]
    
    0 讨论(0)
提交回复
热议问题