python - 我在 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)
当我运行代码时没有错误,但数字似乎没有附加到我的新列表中,并且它像这样显示为空白[]
:
解决方案
最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
,如果是,则添加el
到dup_sorted
列表中。
列表推导可能很难理解,但互联网上有很多关于它们的信息。祝你学习 Python 好运!
推荐阅读
- java - 读取输入消息时出现 I/O 错误;嵌套异常是 java.io.IOException: Stream closed
- jquery - CSS3/具有可变宽度子元素的无限垂直滚动轮播
- c# - 使用反射从 C# 中嵌套类型的 DeclaringType 获取泛型类型
- sql - SQL - 如何检索与非唯一条目相对应的唯一整数的计数?
- python - 无法使用 python selenium 抓取下一页(分页)
- javascript - 启用 DatePicker 的特定日期
- libcurl - libcurl POST xml 文件到 url
- javascript - 我想要 Masonry.js 的 3 列
- asp.net-core - appsettings.json 中的重复元素
- sql - 将 ROWS 拆分为多个 COLUMN