开发者

How do I filter out only items from a list which is in an even position?

Instead of processing items based on its value, I need to run a function based on the item's position. This is an example of filtering based on the 开发者_JAVA技巧content of the list.

only_words = filter(str.isalpha, my_list)

I want to create a slice of the list that contains only items in the even position, that is:

new_list = []
pos = 0
for item in my_list:
   if pos % 2 == 0:
       new_list.append(item)

This is way too ugly. Better suggestions ?


You can use this: my_list[::2] (for odd — my_list[1::2])


[v for k, v in enumerate(mylist) if k % 2 == 0]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜