使用pop()在Python中进行列表操作 [英] List Manipulation in Python with pop()

查看:147
本文介绍了使用pop()在Python中进行列表操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之,我需要根据其索引从列表中删除多个项目.但是,我不能使用pop,因为它会移动索引(没有一些笨拙的补偿系统).有没有办法同时删除多个项目?

In short, I need to remove multiple items from a list according to their indexes. However, I can't use pop because it shifts the indexes (without some clumsy compensating system). Is there a way to remove multiple items simultaneously?

我有一个遍历列表的算法,如果条件合适,则通过pop方法删除该项目.看到所有问题都循环完成后,就会出现问题.弹出完成后,列表将缩短一,将所有值替换一.因此,循环将超出范围.是否可以同时删除多个项目或其他解决方案?

I have an algorithm that goes through a list, and if the conditions are right removes that item via the pop method. A problem arises seeing as this is all done in a loop. Once pop is done the list is shortened by one, displacing all the values by one. So the loop will go out of range. Is it possible to remove multiple items simultaneously, or another solution?

我的问题的一个例子:

L = ['a', 'b', 'c', 'd']

for i in range(len(L)):
    print L
    if L[i] == 'a' or L[i] == 'c':
        L.pop(i)

推荐答案

您的列表很大吗?如果是这样,请使用 itertools 中的ifilter来过滤掉您不希望使用的元素懒惰地想要(没有前期费用).

Are your lists large? If so, use ifilter from itertools to filter out elements that you don't want lazily (with no up front cost).

列表不那么大?只需使用列表理解即可:

Lists not so large? Just use a list comprehension:

 newlist = [x for x in oldlist if x not in ['a', 'c'] ]

这将创建列表的新副本.除非您真正关心内存消耗,否则通常这不是效率问题.

This will create a new copy of the list. This is not generally an issue for efficiency unless you really care about memory consumption.

作为一种语法方便和懒惰的快乐媒介(=大列表的效率),您可以使用( )而不是[ ]来构造生成器而不是列表:

As a happy medium of syntax convenience and laziness ( = efficiency for large lists), you can construct a generator rather than a list by using ( ) instead of [ ]:

interestingelts = (x for x in oldlist if x not in ['a', 'c'])

此后,您可以遍历interestingelts,但是不能对其进行索引:

After this, you can iterate over interestingelts, but you can't index into it:

 for y in interestingelts:    # ok
    print y

 print interestingelts[0]     # not ok: generator allows sequential access only

这篇关于使用pop()在Python中进行列表操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆