程序在数组中查找重复项并将它们放在python中的唯一项之后? [关闭]

问题描述 投票:-2回答:1

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

python duplicates
1个回答
1
投票

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

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]
© www.soinside.com 2019 - 2024. All rights reserved.