从列表中删除项目

时间:2010-07-21 12:25:11

标签: python list unique

嘿,我试图从列表中删除一个项目(不使用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))

set函数工作正常,但我想应用此方法。除了我得到:

 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 个答案:

答案 0 :(得分:5)

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

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

在输入循环之前评估range函数一次,创建列表中所有索引的列表。每次调用remove都会将列表缩短一个,因此如果删除任何元素,则可以保证在列表末尾显示错误。

如果你想使用这样的循环,请尝试:

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

我修了一些其他的东西:

  1. Python if语句中的条件不需要括号。
  2. 如果您发现重复,则不希望进入下一次迭代,因为您将错过两次以上重复的潜在运行。
  3. 你想从索引1开始,而不是零,因为k = 0将访问list1 [-1]。

答案 1 :(得分:3)

答案 2 :(得分:2)

而不是删除项目在新列表中写下所需内容的列表理解:

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

您的方法会中断,因为您从列表中删除了项目。当您这样做时,列表变为更短,并且下一个循环迭代已跳过一个项目。比如你看k = 0和L = [1,2,3]。你删除了第一项,所以L = [2,3],下一个k = 1。所以你看看L [1]是3 - 你跳过了2!

所以:永远不要更改您迭代的列表

答案 3 :(得分:1)

您可以使用del

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