Ell*_*lla 0 python list duplicates
如何在不更改顺序的情况下删除重复的二维列表?
list_j = [[100,2,3,3], [4,98,99,98], [5,99,98,4], [5,99,98,5], [100,99,98,100,100,6]]
list_pre = [list(set(i)) for i in list_j]
print(list_pre)
[[2, 3, 100], [98, 99, 4], [98, 99, 4, 5], [98, 99, 5], [98, 99, 100, 6]]
Run Code Online (Sandbox Code Playgroud)
如您所见,它更改了顺序。我想要的是[[100,2,3,],...]
期望输出 [[100,2,3,], [4,98,99], [5,99,98,4], [5,99,98], [100,99,98,6]]
使用OrderedDict维护键的插入顺序:
from collections import OrderedDict
list_j = [[100,2,3,3], [4,98,99,98], [5,99,98,4], [5,99,98,5], [100,99,98,100,100,6]]
output = [list(OrderedDict.fromkeys(x)) for x in list_j]
Run Code Online (Sandbox Code Playgroud)
给
[[100, 2, 3], [4, 98, 99], [5, 99, 98, 4], [5, 99, 98], [100, 99, 98, 6]]
Run Code Online (Sandbox Code Playgroud)
如果您使用 Python 3.7 或更高版本,您也可以使用普通字典,因为它们也保持插入顺序:
output = [list(dict.fromkeys(x)) for x in list_j]
Run Code Online (Sandbox Code Playgroud)