python列表取出奇数项,从Python中的列表中删除奇数索引元素

本文介绍了一种从Python列表中高效移除奇数索引位置元素的方法,避免了直接迭代过程中删除元素导致的问题,并提供了使用切片和列表推导的替代方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?

解决方案

You can delete all odd items in one go using a slice:

del lst[1::2]

Demo:

>>> 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']

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.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值