gpt4 book ai didi

python - 如何在 Python 中按索引从列表中删除 n 个元素?

转载 作者:太空宇宙 更新时间:2023-11-04 06:49:05 32 4
gpt4 key购买 nike

让我们假设,

g = ['1', '', '2', '', '3', '', '4', '']

我想从 g 中删除所有 '',我必须从那里获取

g = ['1', '2', '3', '4']

最佳答案

>>> g = ['1', '', '2', '', '3', '', '4', '']
>>> filter(None, g)
['1', '2', '3', '4']

Help on built-in function filter in module `__builtin__`:filter(...)filter(function or None, sequence) -> list, tuple, or string   Return those items of sequence for which function(item) is true.  If   function is None, return the items that are true.  If sequence is a tuple   or string, return the same type, else return a list.

You can also use a list comprehension if you prefer

>>> [x for x in g if x!=""]
['1', '2', '3', '4']

关于python - 如何在 Python 中按索引从列表中删除 n 个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9528438/

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