从列表中删除项目

发布于 2024-09-10 10:53:18 字数 1083 浏览 7 评论 0原文

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

Hey, I was trying to delete an item form a list (without using 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))

The set function works fine, but i want to apply this method. Except I get:

 IndexError: list index out of range

on the statement:

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

Edited to add
(Thanks to Ned Batchelder) the working code is:

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))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

_畞蕅 2024-09-17 10:53:18

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

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]。

Your code doesn't work because in your loop, you are iterating over all the indexes in the original list, but shortening the list as you go. At the end of the iteration, you will be accessing indexes that no longer exist:

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

The range function is evaluated once before the loop is entered, creating a list of all the indexes in the list. Each call to remove shortens the list by one, so if you remove any elements, you're guaranteed to get your error at the end of the list.

If you want to use a loop like this, try:

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

I fixed a few other things:

  1. You don't need parentheses around the condition in Python if statements.
  2. 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.
  3. You want to start from index 1, not zero, since k=0 will access list1[-1].
若相惜即相离 2024-09-17 10:53:18

看起来好像您正在尝试统一列表(澄清会很棒),所以请看这里: http://www.peterbe.com/plog/uniqifiers-benchmark

这里也有这个问题:在 Python 中,从列表中删除重复项以使所有元素都是唯一的最快算法是什么 *while保持秩序*?

It looks as if you're trying to uniquify a list (clarification would be awesome) so take a look here: http://www.peterbe.com/plog/uniqifiers-benchmark

There is also this question here on SO: In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique *while preserving order*?

不念旧人 2024-09-17 10:53:18

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

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!

所以:永远不要改变你迭代的列表

Instead of removing items Write a list comprehension of the things you want in the new list:

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

Your method breaks because you remove items from the list. When you do that, the list becomes shorter and the next loop iteration has skipped a item. Say you look at k=0 and L = [1,2,3]. You delete the first item, so L = [2,3] and the next k=1. So you look at L[1] which is 3 -- you skipped the 2!

So: Never change the list you iterate on

甜扑 2024-09-17 10:53:18

您可以使用 del

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

You can use del :

l = [1, 2, 3, 4]
del l[2]
print l
[1, 2, 4]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文