Splitting a list into two seperate lists, by every other item in python

倖福魔咒の 提交于 2021-02-10 18:27:18

问题


Hello I have a quick question I cant seem to solve.

I have a list:

a = [item1, item2, item3, item4, item5, item6]

And I want to split this list into two seperate ones by everything other item such that:

b = [item1, item3, item5]
c = [item2, item4, item6]

回答1:


Use slicing, specifying a step:

b,c = a[::2], a[1::2]



回答2:


Using filter is one option:

a = [item1, item2, item3, item4, item5, item6]
b = filter(lambda x: a.index(x) % 2 == 0, a)
c = filter(lambda x: a.index(x) % 2 != 0, a)

EDIT: This would require for the elements to be unique and is inefficient.



来源:https://stackoverflow.com/questions/22162074/splitting-a-list-into-two-seperate-lists-by-every-other-item-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!