在不更改订单的情况下在列表末尾附加重复项

时间:2016-09-26 07:44:08

标签: python python-2.7 scripting

我是python的新手,并试图在不改变顺序的情况下在列表末尾附加重复的项目

testlist = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56]

def duplicate(alist):
    p = len(alist)
    duplicate = False
    for i in range(0, p):
        for j in range (i + 1, p):
            if alist[i] == alist[j]:
                b = alist.index(alist[j])
                a = alist.pop(b)
                alist.append(a)
                p -= 1
                duplicate = True

    print alist

if duplicate == False:
    print "No duplicate item found"

duplicate(testlist)

输出:[32, 8, 1, 17, 5, 2, 42, 13, 56, 1, 2]

期望的输出:[1, 2, 32, 8, 17, 5, 42, 13, 56, 1, 2]

任何帮助我在这里做错了什么

4 个答案:

答案 0 :(得分:2)

我认为在这种情况下,与原始列表中的排列相比,创建新列表更有效,更清晰:

testlist = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56]

def duplicate(alist):

    filtered, duplicates = [], []
    for element in alist:
        if element in filtered:
            duplicates.append(element)
            continue
        filtered.append(element)

    if not duplicates:
        print "No duplicate item found"
        return alist
    return filtered + duplicates

new_list = duplicate(testlist)
print new_list

答案 1 :(得分:0)

您可以使用“集合”模块获取OrderedDict以维护元素的顺序。

我们在这里使用的技术是创建一个字典来存储数组中每个元素的出现次数,并使用dict查找出现的次数以供以后使用。

for循环中,我们使用dict方法查看get中是否已存在元素。如果true那么我们增加计数器,否则将计数器初始化为零。

import collections
lst = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56]

# Create a dictionary storing the the number of occurences
occurences_dict = collections.OrderedDict()
for i in lst:
    occurences_dict[i] = occurences_dict.get(i, 0) + 1

final = occurences_dict.keys() + [k for k, v in occurences_dict.items() if v>1]

print final
>>> [1, 2, 32, 8, 17, 5, 42, 13, 56, 1, 2]

答案 2 :(得分:0)

我这样解决了。我也进行了一些更改,使代码更加Pythonic。

test_list = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56]

def duplicate(a_list):
    list_length = len(a_list)
    duplicate = False
    checked = []
    for i in range(list_length):
        if a_list.count(a_list[i]) > 1:
            if a_list[i] not in checked:
                duplicate = True
                a_list.append(a_list[i])
                checked.append(a_list[i])
    if duplicate == False:
        print("No duplicate item found")
        return None
    return a_list

print(duplicate(test_list))

答案 3 :(得分:0)

不是检查值,而是比较索引。

请检查此代码:

testlist = [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56,32]

print("Original list - ",testlist)
tmp_list = []
exclude =[]
for i in range(len(testlist)):
    if i == testlist.index(testlist[i]):

        tmp_list.append(testlist[i])
    else:
        exclude.append(testlist[i])
tmp_list.extend(exclude)
testlist = tmp_list

print("Updated list - ",testlist)

输出:

C:\Users\dinesh_pundkar\Desktop>python c.py
Original list -  [1, 2, 32, 8, 1, 17, 5, 2, 42, 13, 56, 32]
Updated list -  [1, 2, 32, 8, 17, 5, 42, 13, 56, 1, 2, 32]

C:\Users\dinesh_pundkar\Desktop>