【问题标题】:Python: items not being removed from listPython:未从列表中删除的项目
【发布时间】:2017-04-04 12:19:23
【问题描述】:
listsal2 = [1,2,2,3,3,4,5,6,7,8]
listsal3 = []

counter = 0
for i in listsal2:
    item = listsal2.count(i)

    if item > 1:
        counter = item 
        while counter > 1:
            listsal3.append(i)   
            counter = counter - 1




print (listsal3)

我一直在研究模式功能,但由于某种原因,它会保留列表中的最后几个数字,并且列表中的项目越多,未删除的项目就越多。

编辑:刚刚意识到我忘记了现在的第二部分代码

EDIT2:代码被缩小并且更易于阅读

EDIT3:更改了代码,因此重复的数字进入了一个新列表,但它具有多个列表项的数量

感谢大家的帮助,我想我现在明白了

【问题讨论】:

  • a = a - 你希望它做什么?
  • 调试你的代码,你会立即发现问题。
  • if a > b - 您将 a 设置为 0 并将 b 设置为非负数。 a 怎么可能大于 b
  • @user2357112 a = a 的原因是因为有时列表不会被组织,所以 a 可能大于新的 b 值
  • 在迭代列表时删除列表的元素会中断迭代。不要修改for循环中的listsal2

标签: python list mode


【解决方案1】:

您在迭代列表时正在修改它。通常不建议这样做,因为它会破坏迭代。

如果您要删除所有单个和重复的元素,下面的代码就可以了:

l = listsal2
l = [v for i, v in enumerate(l) if l.count(v) > 1 and l.index(v) == i]

这会保留原始列表中的顺序。

【讨论】:

    【解决方案2】:

    在您的情况下,即使您考虑过一次i=2,您也会再次浏览列表 2,因为它存在多次。这就是为什么 2 和 3 两次出现在 listsal3 中的原因。相反,您想要做的只是为每个独特的项目浏览一次列表。

    listsal2 = [1,2,2,3,3, 4]
    newlist = set(listsal2)
    listsal3 = []
    
    counter = 0
    for i in newlist:
        item = listsal2.count(i)
    
        if item > 1:
            counter = item 
            print counter
            while counter > 1:
                listsal3.append(i)   
                counter = counter - 1
    
    print listsal2, listsal3
    

    要从列表中获取唯一项目,请将其转换为集合。

    另一种方法: 只需保留一个包含每个唯一元素计数的列表,取其最大值,然后追溯到它对应的元素。

    newset = set(listsal2)
    newlist = list(set)
    counts = []
    
    for item in newlist:
        counts.append(listsal2.count(item))
    maxcount = max(counts)
    max_occurring_item = newlist[counts.index(maxcount)]
    

    【讨论】:

      猜你喜欢
      • 2022-12-20
      • 1970-01-01
      • 1970-01-01
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      • 2013-08-03
      相关资源
      最近更新 更多