从Python中的列表中删除奇数索引元素 [英] Remove odd-indexed elements from list in Python

查看:2260
本文介绍了从Python中的列表中删除奇数索引元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从列表中删除奇数索引的元素(其中零被视为偶数),但是以这种方式删除它们将不起作用,因为它会抛弃索引值.

I'm trying to remove the odd-indexed elements from my list (where zero is considered even) but removing them this way won't work because it throws off the index values.

lst = ['712490959', '2', '623726061', '2', '552157404', '2', '1285252944', '2', '1130181076', '2', '552157404', '3', '545600725', '0']


def remove_odd_elements(lst):
    i=0
    for element in lst:
        if i % 2 == 0:
            pass
        else:
            lst.remove(element)
        i = i + 1

如何遍历列表并干净地删除那些索引奇数的元素?

How can I iterate over my list and cleanly remove those odd-indexed elements?

推荐答案

您可以使用演示:

>>> lst = ['712490959', '2', '623726061', '2', '552157404', '2', '1285252944', '2', '1130181076', '2', '552157404', '3', '545600725', '0']
>>> del lst[1::2]
>>> lst
['712490959', '623726061', '552157404', '1285252944', '1130181076', '552157404', '545600725']

在迭代列表时,不能从列表中删除元素,因为列表迭代器在删除项目时不会进行调整.参见循环"Forgets"删除一些项目尝试时会发生什么情况.

You cannot delete elements from a list while you iterate over it, because the list iterator doesn't adjust as you delete items. See Loop "Forgets" to Remove Some Items what happens when you try.

一种替代方法是使用 enumerate() 提供索引:

An alternative would be to build a new list object to replace the old, using a list comprehension with enumerate() providing the indices:

lst = [v for i, v in enumerate(lst) if i % 2 == 0]

保留偶数元素,而不是删除奇数元素.

This keeps the even elements, rather than remove the odd elements.

这篇关于从Python中的列表中删除奇数索引元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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