gpt4 book ai didi

python - 不从列表中删除

转载 作者:太空宇宙 更新时间:2023-11-04 08:11:54 25 4
gpt4 key购买 nike

我正在处理下一个代码:

for u in G:
if u.count('L')>1:
while (u in G)==True:
G.remove(u)
print G

其中 G 是包含字母 O、A 和 L 的字符串列表。问题是,当 u.count('L') 大于 1 时,对象 u 不会从列表中消失。我该如何修复?谢谢。

[编辑]我正在使用的列表示例如下:https://www.dropbox.com/s/qiv2jq4xlg0d5sg/list.txt

最佳答案

您似乎在尝试删除其中包含多个连续“L”的单词。

输入:['ALL', 'APPLE', 'LLAMA', 'LAX', 'PALLOR']

输出:['APPLE', 'LAX']

这里有一些方法:

列表理解

lyst[:] = [word for word in lyst if 'LL' not in word]

([:] 部分表示 to put the new list in the same place the old one was 。对于小型列表来说这不是很重要,但会让您看起来知道自己在做什么。)

过滤器

lyst = filter(lambda word: 'LL' not in word, lyst)

(您可以在 Python 2 中使用 filter 再次执行 [:] 技巧,但在 Python 3 中 filter 不会返回列表,所以我把它遗漏了。)

For循环

如何不这样做:

for i, word in enumerate(lyst):
if 'LL' in word:
del lyst[i]

为什么不呢?它似乎适用于上面的列表,但请查看正在修改的索引:

>>> lyst = ['ALL', 'APPLE', 'LLAMA', 'LAX', 'PALLOR']
>>> for i,w in enumerate(lyst):
... print i,w
... if 'LL' in w:
... del lyst[i]
...
0 ALL
1 LLAMA
2 PALLOR

这样不好! “LLAMA”的索引不是从 1 开始的。我们可以通过更改输入列表来破解此算法:

>>> lyst=['APPLE', 'ALL', 'LLAMA', 'LAX', 'PALLOR']
>>> for i,w in enumerate(lyst):
... print i,w
... if 'LL' in w:
... del lyst[i]
...
0 APPLE
1 ALL
2 LAX
3 PALLOR
>>> lyst
['APPLE', 'LLAMA', 'LAX']

列表理解或过滤方法可能是最好的,但如果你真的喜欢写出你的循环,你必须反过来以避免索引从你下面改变:

>>> for i, w in reversed(list(enumerate(lyst))):
... print i,w
... if 'LL' in w:
... del lyst[i]
...
4 PALLOR
3 LAX
2 LLAMA
1 ALL
0 APPLE
>>> lyst
['APPLE', 'LAX']

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

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