用偶数和奇数索引将列表分成两半? [英] Split a list into half by even and odd indexes?
问题描述
可能的重复:
Python程序,用于将列表分为两部分具有交替元素的列表
我有一个这样的列表:
list1 = [blah, 3, haha, 2, pointer, 1, poop, fire]
我想要的输出是:
list = [3, 2, 1, fire]
所以我想要的是列出前一个列表中的偶数元素.我尝试使用 for
语句,并尝试在将第2n个元素追加到列表时删除它们,但是没有成功:
So what I want is to make a list of even elements of the former list. I tried using a for
statement and tried to delete 2nth element while appending them to the list, but it didn't work out:
count = 0
for a in list1:
list2.append(a)
if count % 2 = = 1:
list2.pop(count)
print list2
有什么建议吗?
推荐答案
这应该可以为您提供所需的信息-定期从偏移量0或1采样列表:
This should give you what you need - sampling a list at regular intervals from an offset 0 or 1:
>>> a = ['blah', 3,'haha', 2, 'pointer', 1, 'poop', 'fire']
>>> a[0:][::2] # even
['blah', 'haha', 'pointer', 'poop']
>>> a[1:][::2] # odd
[3, 2, 1, 'fire']
请注意,在上面的示例中,第一个切片操作( a [1:]
)演示了从所需起始索引中选择所有元素的方法,而第二个切片操作( a [::2]
) 演示了如何选择列表中的所有其他项目.
Note that in the examples above, the first slice operation (a[1:]
) demonstrates the selection of all elements from desired start index, whereas the second slice operation (a[::2]
) demonstrates how to select every other item in the list.
一种更加惯用和高效的切片操作将两者合并为一个,即 a [:: 2]
(可以省略 0
)和 a [1:: 2]
,它避免了不必要的列表复制,应该在生产代码中使用,就像其他人在评论中指出的那样.
A more idiomatic and efficient slice operation combines the two into one, namely a[::2]
(0
can be omitted) and a[1::2]
, which avoids the unnecessary list copy and should be used in production code, as others have pointed out in the comments.
这篇关于用偶数和奇数索引将列表分成两半?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!