[英]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.