gpt4 book ai didi

Python - 从列表中删除项目

转载 作者:太空狗 更新时间:2023-10-29 20:11:45 24 4
gpt4 key购买 nike

# I have 3 lists:
L1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
L2 = [4, 7, 8]
L3 = [5, 2, 9]
# I want to create another that is L1 minus L2's memebers and L3's memebers, so:
L4 = (L1 - L2) - L3 # Of course this isn't going to work

我想知道,执行此操作的“正确”方法是什么。我可以用很多不同的方式来做,但是 Python 的风格指南说每件事应该只有一种正确的方式。我从来不知道这是什么。

最佳答案

这里有一些尝试:

L4 = [ n for n in L1 if (n not in L2) and (n not in L3) ]  # parens for clarity

tmpset = set( L2 + L3 )
L4 = [ n for n in L1 if n not in tmpset ]

现在我有时间思考了,我意识到 L2 + L3 这件事创建了一个临时列表,该列表会立即被丢弃。所以更好的方法是:

tmpset = set(L2)
tmpset.update(L3)
L4 = [ n for n in L1 if n not in tmpset ]

更新:我看到一些关于性能的夸大说法,我想断言我的解决方案已经尽可能快了。创建中间结果,无论它们是中间列表还是中间迭代器,然后必须重复调用,总是比简单地为集合提供 L2L3 更慢像我在这里所做的那样直接迭代。

$ python -m timeit \
-s 'L1=range(300);L2=range(30,70,2);L3=range(120,220,2)' \
'ts = set(L2); ts.update(L3); L4 = [ n for n in L1 if n not in ts ]'
10000 loops, best of 3: 39.7 usec per loop

所有其他替代方案(我能想到的)必然比这慢。例如,我们自己执行循环,而不是让 set() 构造函数执行它们,会增加开销:

$ python -m timeit \
-s 'L1=range(300);L2=range(30,70,2);L3=range(120,220,2)' \
'unwanted = frozenset(item for lst in (L2, L3) for item in lst); L4 = [ n for n in L1 if n not in unwanted ]'
10000 loops, best of 3: 46.4 usec per loop

使用迭代器,它们涉及的所有状态保存和回调显然会更加昂贵:

$ python -m timeit \
-s 'L1=range(300);L2=range(30,70,2);L3=range(120,220,2);from itertools import ifilterfalse, chain' \
'L4 = list(ifilterfalse(frozenset(chain(L2, L3)).__contains__, L1))'
10000 loops, best of 3: 47.1 usec per loop

所以我相信我昨晚给出的答案仍然是 far and away(显然对于大于 5µsec 的“far and away”的值)最好的,除非提问者在 L1 并希望每次重复出现在其他列表之一中时将它们删除一次。

关于Python - 从列表中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3947654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com