我在数组中有整数元素序列" 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
这样的内置函数,但是它安排了
结果序列按升序排列,我希望保持顺序不变。
有人可以帮忙吗?
答案 0 :(得分:3)
您可以使用sort = 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]
答案 1 :(得分:0)
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]`