gpt4 book ai didi

python - 从列表中删除重复的数字

转载 作者:行者123 更新时间:2023-11-28 20:55:52 25 4
gpt4 key购买 nike

我试图删除列表中的所有重复数字。

我试图了解我的代码有什么问题。

numbers = [1, 1, 1, 1, 6, 5, 5, 2, 3]
for x in numbers:
if numbers.count(x) >= 2:
numbers.remove(x)
print(numbers)

我得到的结果是:

[1, 1, 6, 5, 2, 3]

最佳答案

我想这个想法是在不使用库函数的情况下自己编写代码。然后我仍然会建议使用额外的集合结构来存储您以前的项目并且只在您的数组上进行一次:

numbers = [1, 1, 1, 1, 6, 5, 5, 2, 3]
unique = set()
for x in numbers:
if x not in unique:
unique.add(x)
numbers = list(unique)
print(numbers)

如果你想使用你的代码,那么问题是你在每个循环中修改集合,这在大多数编程语言中是一个很大的禁忌。尽管 Python 允许您这样做,但问题和解决方案已在此答案中描述:How to remove items from a list while iterating? :

Note: There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g.,

for x in a[:]:
if x < 0: a.remove(x)

关于python - 从列表中删除重复的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55724127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com