繁体   English   中英

有条件地附加到列表中

[英]Conditionally appending in the list

我有'n'个列表让我们说:

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]

预期结果:

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

我希望代码在每个列表和 append 中查找前两个元素,前提是这两个元素不相同:

这给出了所需的 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]]

这怎么样?

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)

暂无
暂无

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

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