python 如何删除数组中重复的元素保持顺序不变?
How to delete repeated elements from array keeping the order unchanged in python?
我在数组 "a" 中有整数元素序列,如下所示
a=[2,1,5,4,8,4,2,1,2,4,8,6,1,5,4,87,62,3]
我需要像
这样的输出
output=[2,1,5,4,8,6,87,62,3]
我尝试了 set
或 unique
等内置函数,但它安排了
结果序列按升序排列,我想保持顺序不变。
有人能帮忙吗?
a=[2,1,5,4,8,4,2,1,2,4,8,6,1,5,4,87,62,3]
b = []
您可以使用
[b.append(x) for x in a if x not in b]
或更容易阅读
for x in a:
if x not in b:
b.append(x)
>>> [2, 1, 5, 4, 8, 6, 87, 62, 3]`
您可以使用 sorted with key=list.index
>>> a=[2,1,5,4,8,4,2,1,2,4,8,6,1,5,4,87,62,3]
>>> new_a = sorted(set(a), key=a.index)
>>> new_a
[2, 1, 5, 4, 8, 6, 87, 62, 3]
我在数组 "a" 中有整数元素序列,如下所示
a=[2,1,5,4,8,4,2,1,2,4,8,6,1,5,4,87,62,3]
我需要像
这样的输出output=[2,1,5,4,8,6,87,62,3]
我尝试了 set
或 unique
等内置函数,但它安排了
结果序列按升序排列,我想保持顺序不变。
有人能帮忙吗?
a=[2,1,5,4,8,4,2,1,2,4,8,6,1,5,4,87,62,3]
b = []
您可以使用
[b.append(x) for x in a if x not in b]
或更容易阅读
for x in a:
if x not in b:
b.append(x)
>>> [2, 1, 5, 4, 8, 6, 87, 62, 3]`
您可以使用 sorted with key=list.index
>>> a=[2,1,5,4,8,4,2,1,2,4,8,6,1,5,4,87,62,3]
>>> new_a = sorted(set(a), key=a.index)
>>> new_a
[2, 1, 5, 4, 8, 6, 87, 62, 3]