![](/img/trans.png)
[英]Why is my code for sorting a list via reduce in Python throwing an error?
[英]problems in my list sorting code in 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 好运!
我不明白你想要什么,但你基本上可以像这样对列表进行排序
print(sorted(randomDup_list))
你可以像这样创建你的新列表
dup_sorted = sorted(randomDup_list)
print(dup_sorted)
大家好,欢迎学习python。 我已经编码了几年,但我仍然使用print
来测试我的逻辑。
让我们分解您的代码并将print
添加到每个逻辑测试
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:
print("start iteration")
if len(randomDup_list) == 0:
print("1 true")
dup_sorted.append(x)
counter +=1
elif x != randomDup_list[counter]:
print("2 true")
print(dup_sorted)
for y in dup_sorted:
if y != x:
print("3 true")
dup_sorted.append(x)
print("stop iteration")
print(dup_sorted)
如果您运行此代码,您将看到第一个逻辑测试在您的示例中永远不会成立。 因此它将 go 进行第二次逻辑测试。 这最终将评估为 true,但将跳过一些迭代。 start iteration stop iteration
。 对于最后一个逻辑测试,这永远不会是真的,因为 dup_sorted 将始终为空。 所以for y in dup_sorted
将一无所获。
我也认为sort out
是模棱两可的。 是排序吗? 筛选?
您可以执行set(randomDup_list)
过滤重复项
你可以做sorted(randomDup_list)
来整理列表
您可以对排序的过滤列表执行sorted(list(set(randomDup_list))
看到你的新评论
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 x in dup_sorted:
continue
else:
dup_sorted.append(x)
print(dup_sorted)
这会初始化一个空列表。 循环浏览您的列表。 检查它是否存在,如果不存在则追加。 由于 List 保持顺序,您可以期望顺序不会改变。
从列表中删除任何重复项而不更改顺序
代码
dup_sorted = []
for x in randomDup_list:
if not x in dup_sorted: # check if x is in output yet
dup_sorted.append(x) # add x to output
print(dup_sorted)
# Output: [0, 3, 1, 9, 8, 2, 4, 5, 6, 7]
你可以使用这个:
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 = []
dup_sorted.append(randomDup_list[0])
for x in range(len(randomDup_list)):
temp = 0
for y in range(len(dup_sorted)):
if randomDup_list[x] != dup_sorted[y]:
temp = temp + 1
if temp == len(dup_sorted):
dup_sorted.append(randomDup_list[x])
print(dup_sorted)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.