程序查找数组中的重复项并将其放置在python中唯一的重复项之后?

时间:2019-02-27 03:01:45

标签: python duplicates

我已经尝试了很多次来解决这个问题,但是没有得到正确的答案。

1 个答案:

答案 0 :(得分:1)

这是一个非常简单的四步解决方案:

arr = [1, 2, 5, 2, 7, 3, 2, 1, 4, 4, 2, 3, 6, 9, 0]

# isolate unique elements by casting the list to a set
uniques_set = list(set(arr))

# create a list of just duplicates, by removing all unique elements once
duplicates = arr[:]
for u in uniques:
    duplicates.remove(u)

# remove all the duplicate elements from the end of the original list, to get all unique elements in order
# do this by reversing the list, removing from the front, and then re-reversing it
reordered = arr[::-1]
for d in duplicates:
    reordered.remove(d)
reordered = reordered[::-1]

# reinsert duplicate elements immediately after reordered elements
for d in duplicates:
    reordered.insert(reordered.index(d) + 1, d)

运行该代码会产生以下结果:

[1, 1, 2, 2, 2, 2, 5, 7, 3, 3, 4, 4, 6, 9, 0]