Python list去重且保持原顺序不变的方法(sorted or sort)

一、 可行的方法

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]

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值