简体   繁体   中英

Conditionally appending in the list

I have 'n' lists let's say:

L1=[1,2,3,4]
L2=[1,2,4,5]
L3=[2,1,3,4]
L4=[4,3,1,2]
L5=[2,1,4,5]
L6=[1,3,4,5]

Expected result:

[[1,2,3,4],[2,1,3,4],[4,3,1,2],[1,3,4,5]]

I want the code to look for first two elements in every list and append only if both these two elements aren't same:

This gives the desired output:

L1=[1,2,3,4]
L2=[1,2,4,5]
L3=[2,1,3,4]
L4=[4,3,1,2]
L5=[2,1,4,5]
L6=[1,3,4,5]

output = []
tmp_set = set()
for list_ in [L1, L2, L3, L4, L5, L6]:
    x1, x2 = list_[:2]
    if not (x1, x2) in tmp_set:
        tmp_set.add((x1, x2))
        output.append(list_)
print(output)

#[[1, 2, 3, 4], [2, 1, 3, 4], [4, 3, 1, 2], [1, 3, 4, 5]]

How is this?

class SpecialList(list):
    def __init__(self, x=[]):
        self.memory = set()
        super().__init__(x)
    def append(self, x):
        x1, x2 = x[:2]
        if not (x1, x2) in self.memory:
            self.memory.add((x1, x2))
            super().append(x)

x = SpecialList()
x.append([1,2,3,4])
x.append([1,2,4,5])
x.append([2,1,3,4])
x.append([4,3,1,2])
x.append([2,1,4,5])
x.append([1,3,4,5])

print(x)

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