代码之家  ›  专栏  ›  技术社区  ›  Mahmoud

从列表中删除项目

  •  0
  • Mahmoud  · 技术社区  · 14 年前

    嘿,我想从列表中删除一个项目(不使用 set ):

    list1 = []
    for i in range(2,101):
        for j in range(2,101):
            list1.append(i ** j)
    list1.sort()
    for k in range(1,len(list1) - 1):
        if (list1[k] == list1[k - 1]):
            list1.remove(list1[k])
    print "length = " + str(len(list1))
    

    这个 函数运行良好,但我想应用此方法。但我得到:

     IndexError: list index out of range
    

     if (list1[k] == list1[k - 1]):
    

    编辑以添加 (感谢Ned Batchelder)工作代码是:

    list1 = []
    for i in range(2,101):
     for j in range(2,101):
       list1.append(i ** j)
    list1.sort()
    k = 0
    while k < len(list1) - 1: # while loop instead of for loop because "The range function is evaluated once before the loop is entered"
     k += 1
     if (list1[k] == list1[k - 1]):
      list1.remove(list1[k])
      list1.sort()
      k -= 1 # "If you find a duplicate, you don't want to move onto the next iteration, since you'll miss potential runs of more than two duplicates"
    print "length = " + str(len(list1))
    
    4 回复  |  直到 10 年前
        1
  •  5
  •   Ned Batchelder    14 年前

    您的代码不起作用,因为在循环中,您正在迭代原始列表中的所有索引,但会随着时间的推移而缩短列表。在迭代结束时,您将访问不再存在的索引:

    for k in range(1,len(list1) - 1):
        if (list1[k] == list1[k - 1]):
            list1.remove(list1[k])
    

    range 函数在进入循环之前被求值一次,从而创建列表中所有索引的列表。每次呼叫 remove 将列表缩短1,因此如果删除任何元素,则肯定会在列表末尾得到错误。

    k = 1
    while k < len(list1):
        if list1[k] == list1[k-1]:
            del list1[k]
        else:
            k += 1
    

    我还做了其他一些事情:

    1. 如果您发现一个重复的,您就不想进入下一个迭代,因为您将错过两个以上重复的潜在运行。
    2. 您希望从索引1开始,而不是从零开始,因为k=0将访问list1[-1]。
        2
  •  3
  •   Community CDub    7 年前

    看起来好像你在试图将一个列表单列出来(澄清将是很棒的),所以看看这里: http://www.peterbe.com/plog/uniqifiers-benchmark

    这里还有一个问题,所以: In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique *while preserving order*?

        3
  •  2
  •   Jochen Ritzel    14 年前

    不要删除项目,而是在新列表中列出您想要的内容:

    list1[:] = [list1[k] for k in range(1,len(list1) - 1) 
                         if not list1[k] == list1[k - 1] ]
    

    更短的

    所以: 千万不要改变你迭代的列表

        4
  •  1
  •   Guillaume Lebourgeois    14 年前

    你可以用 del :

    l = [1, 2, 3, 4]
    del l[2]
    print l
    [1, 2, 4]