从Python列表中删除重复项。

huangapple go评论69阅读模式
英文:

removing a duplicated item from a python list

问题

I'm tring to remove the maximum value from a list that has a repeated maximum value for example: [1,3,6,6,5] the code i use only removes one of the values wihtout removing the other. any ideas why is that happening? the code i use is:

我正在尝试从一个具有重复的最大值的列表中删除最大值,例如:[1,3,6,6,5] 我使用的代码只删除一个值,而没有删除另一个。有什么想法为什么会发生这种情况?我使用的代码是:

n = int(input())
arr = map(int, input().split())
lst = list(arr)
for i in lst:
    if i == max(lst):
        del(lst[lst.index(i)])
print(max(lst))
英文:

I'm tring to remove the maximum value from a list that has a repeated maximum value for example: [1,3,6,6,5]
the code i use only removes one of the values wihtout removing the other. any ideas why is that happening? the code i use is:

    n = int(input())
    arr = map(int, input().split())
    lst = list (arr)
    for i in lst:
        if i == max(lst):
            del(lst[lst.index(i)])
    print (max(lst))

答案1

得分: 1

以下是翻译好的部分:

这段代码存在问题:

for i in lst:
    if i == max(lst):
        del(lst[lst.index(i)])

正如@AllanWind所评论的,当您调用del来从列表中删除项目时,这会改变列表的大小,导致外部的for i in lst循环与实际的列表内容不同步。

在迭代列表时不要添加/删除项目。

对于这种特定用例,下面的代码会更好:

m = max(lst)
while m in lst:
    lst.remove(m)
英文:

This code is the problem:

for i in lst:
    if i == max(lst):
        del(lst[lst.index(i)])

As @AllanWind commented, when you call del to remove the item from the list, this changes the size of the list, which causes the outer for i in lst loop to get out of sync with the actual list contents.

Don't add/remove items to a list as you're iterating over it.

For this specific use case, this code would be a lot better:

m = max(lst)
while m in lst:
    lst.remove(m)

答案2

得分: 0

你可以使用一个筛选器(如果你希望将结果分配给相同的 lst):

lst = [1, 3, 6, 6, 5]
lst2 = list(filter(lambda f: f != max(lst), lst))
英文:

You could use a filter (and if you wish assign the result to the same lst):

lst = [1, 3, 6, 6, 5]
lst2 = list(filter(lambda f: f != max(lst), lst))

huangapple
  • 本文由 发表于 2023年4月17日 08:47:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76031029.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定