pop在python中的用法_使用pop()在Python中进行列表操作

小结使用列表理解(或genexpr)从列表中删除多个项

如果输入的是大字节字符串,则使用str.translate()删除字符

对于大型列表,一次删除一个项del L[i]很慢

如果项是与示例中相同的字节,则可以使用^{}:def remove_bytes(bytestr, delbytes):

"""

>>> remove_bytes(b'abcd', b'ac') == b'bd'

True

"""

return bytestr.translate(None, delbytes)

通常,可以使用切片删除多个项目:def remove_inplace_without_order(L, delitems):

"""Remove all items from `L` that are in `delitems` (not preserving order).

>>> L = list(range(4)); remove_inplace_without_order(L, [0,2]); L

[3, 1]

"""

idel = len(L) # items idel.. to be removed

for i in reversed(range(len(L))):

if L[i] in delitems:

idel -= 1

L[i] = L[idel] # save `idel`-th item

del L[idel:] # remove items all at once

#NOTE: the function returns `None` (it means it modifies `L` inplace)

正如前面提到的@phooji和@senderle那样,列表理解(或生成器表达式)在您的情况下更可取:def remove_listcomp(L, delitems):

return [x for x in L if x not in delitems]

下面是L=list("abcd"*10**5); delitems="ac"的性能比较:| function | time, msec | ratio |

|------------------------------+------------+--------|

| list | 4.42 | 0.9 |

| remove_bytes | 4.88 | 1.0 |

| remove | 27.3 | 5.6 |

| remove_listcomp | 36.8 | 7.5 |

| remove_inplace_without_order | 71.2 | 14.6 |

| remove_inplace_senderle2 | 83.8 | 17.2 |

| remove_inplace_senderle | 15000 | 3073.8 |

#+TBLFM: $3=$2/@3$2;%.1f

其中try:

from itertools import ifilterfalse as filterfalse

except ImportError:

from itertools import filterfalse # py3k

def remove(L, delitems):

return filterfalse(delitems.__contains__, L)

def remove_inplace_senderle(L, delitems):

for i in reversed(range(len(L))):

if L[i] in delitems:

del L[i]

def remove_inplace_senderle2(L, delitems):

write_i = 0

for read_i in range(len(L)):

L[write_i] = L[read_i]

if L[read_i] not in delitems:

write_i += 1

del L[write_i:]

由于使用O(N**2)算法,^{}速度较慢。每一个del L[i]都可能导致右边的所有项向左移动以缩小间隙。

上表中的“时间”列包括创建新输入列表(第一行)所需的时间,这是由于某些算法会修改输入位置。

以下是相同输入但不在每次迭代中创建新列表的计时:| function | time, msec | ratio |

|-----------------+------------+-------|

| remove_bytes | 0.391 | 1 |

| remove | 24.3 | 62 |

| remove_listcomp | 33.4 | 85 |

#+TBLFM: $3=$2/@2$2;%d

该表显示^{}与listcomp相比没有显著改进。

一般来说,考虑此类任务的性能是不值得的,甚至是有害的,除非探查器证明此代码是一个瓶颈,并且对您的程序非常重要。但是了解能够在速度上提供超过一个数量级改进的替代方法可能是有用的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值