Python list去重且保持原顺序不变的方法

Python list去重且保持原顺序不变的方法,第1张

一、 可行的方法 list 去重,顺序乱掉
# normal 写法
l1 = ['b','c','d','b','c','a','a']
l2 = list(set(l1))
print(l2)
 
# plus 写法
l1 = ['b','c','d','b','c','a','a']
l2 = list({}.fromkeys(l1).keys())

output:
[‘b’, ‘d’, ‘c’, ‘a’]
[‘b’, ‘c’, ‘d’, ‘a’]

去重后还是原 list 顺序
# normal 写法
l1 = ['b','c','d','b','c','a','a']
l2 = list(set(l1))
l2.sort(key=l1.index)
 
# plus 写法
l1 = ['b','c','d','b','c','a','a']
l2 = sorted(set(l1),key=l1.index)

output:
[‘b’, ‘c’, ‘d’, ‘a’]
[‘b’, ‘c’, ‘d’, ‘a’]

写循环代码实现
L = [3, 1, 2, 1, 3, 4]
T = L[:]
for i in L:
  while T.count(i) > 1:
    del T[T.index(i)]
T.sort(key=L.index)

output:
[3, 1, 2, 4]

二、为什么可以用index呢,长度都不一致

以如下代码为例:

# normal 写法
l1 = ['b','c','d','b','c','a','a']
l2 = list(set(l1))
print(l2)
l2.sort(key=l1.index)
print(l2)

output:
[‘b’, ‘d’, ‘c’, ‘a’]
[‘b’, ‘c’, ‘d’, ‘a’]

假设:将l2的值作为参数传递给key指定的函数,获取返回的结果,然后根据返回结果大小排序;

l1 = ['b','c','d','b','c','a','a']
l2 = list(set(l1))
print(l2)
for v in l2:
    print(l1.index(v))

output:
[‘b’, ‘d’, ‘c’, ‘a’]
0
2
1
5
再排序:0,2,1,5 --> 0,1,2,5

再看其他案例,证明上述假设:

L = ["cccc", "b", "dd", "aaa"]
print("Normal sort :", sorted(L))
print("Sort with len :", sorted(L, key=len))

output:
Normal sort : [‘aaa’, ‘b’, ‘cccc’, ‘dd’]
Sort with len : [‘b’, ‘dd’, ‘aaa’, ‘cccc’]

# Sort a list of integers based on
# their remainder on dividing from 7
def func(x):
	return x % 7

L = [15, 3, 11, 7]
print("Normal sort :", sorted(L))
print("Sorted with key:", sorted(L, key=func))

output:
Normal sort : [3, 7, 11, 15]
Sorted with key: [7, 15, 3, 11]

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/916428.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存