如何从列表中删除奇数索引元素?

2024-04-26 11:00:32 发布

您现在位置:Python中文网/ 问答频道 /正文

它显示列表索引超出范围。我需要删除所有奇怪的索引元素,但它不工作,显示列表索引超出范围

list1 = [12,33,45,66,75,33,4,56,66,67,1,2]
        for i in range(len(list1)):
            x=i
            if(i%2!=0):
                #print(list1[x])
                list1.remove(list1[x])
            else:
                continue
        print(list1)

Tags: in元素列表forlenifrangeelse
3条回答

解决方案

del list1[1::2]

这是从删除所有奇数索引元素到Python代码的直接翻译

基准测试以及针对包含一百万个元素的列表的向上投票的解决方案:

11.8 ms  11.9 ms  12.0 ms  list1 = list1[::2]
90.1 ms  90.6 ms  91.1 ms  list1 = [i for indexValue, i in enumerate(list1) if indexValue % 2 == 0]
 8.0 ms   8.2 ms   8.2 ms  del list1[1::2]

基准代码(Try it online!):

from timeit import repeat

setup = 'list1 = list(range(10**6))'

solutions = [
    'list1 = list1[::2]',
    'list1 = [i for indexValue, i in enumerate(list1) if indexValue % 2 == 0]',
    'del list1[1::2]',
]

for _ in range(3):
    for solution in solutions:
        times = sorted(repeat(solution, setup, number=1))[:3]
        print(*('%4.1f ms ' % (t * 1e3) for t in times), solution)
    print()

只要这样做,它就会起作用

list1 = [12,33,45,66,75,33,4,56,66,67,1,2]
list1=list1[::2]
print(list1)`

输出:- [12, 45, 75, 4, 66, 1]

问题:

您的代码不适用于给定的代码段,因为每次从list1中删除一个元素时,都会删除该元素的索引

解决方案:

为了使用迭代方法解决这个问题,您需要将偶数元素附加到另一个列表中,或者如Pratyush Arora所述,任何元素都可以工作

如果您使用的是迭代方法,这可能会有所帮助:

代码:

list1 = [12,33,45,66,75,33,4,56,66,67,1,2]

# Using list comprehension
evenIndexList = [i for indexValue, i in enumerate(list1) if indexValue % 2 == 0]
print(evenIndexList)

# Standard approach
newList = []
for i in range(len(list1)):
    if i % 2 == 0:
         newList.append(list1[i])
print(newList)

相关问题 更多 >