首页 > 解决方案 > 我在 python 中的列表排序代码中的问题

问题描述

我想出了这段代码来整理随机排列的数字列表中的重复项。

counter = 0
randomDup_list = [0, 3, 0, 1, 9, 8, 2, 3, 4, 2, 4, 3, 5, 6, 0, 6, 5, 2, 6, 6, 7, 8, 9, 4, 4]
dup_sorted = []
for x in randomDup_list:
    if len(randomDup_list) == 0:
        dup_sorted.append(x)
        counter +=1
    elif x != randomDup_list[counter]:
        for y in dup_sorted:
            if y != x:
                dup_sorted.append(x)
print(dup_sorted)

当我运行代码时没有错误,但数字似乎没有附加到我的新列表中,并且它像这样显示为空白[]

标签: pythonlist

解决方案


最pythonic的方法是使用列表理解,如下所示:

dup_sorted = [el for index, el in enumerate(randomDup_list) if el not in randomDup_list[:index]]

Enumerate 将创建一个元组列表,其中第一个元组元素作为列表中的索引,[(0,0), (1,3), (2,0), ...]在您的情况下是前 3 个元素。

然后它基本上检查列表中是否el第一次出现el,如果是,则添加eldup_sorted列表中。

列表推导可能很难理解,但互联网上有很多关于它们的信息。祝你学习 Python 好运!


推荐阅读