我知道有很多方法可以做到这一点,但我正在寻找一种光滑的pythonic方式来完成以下任务。给出一个数字列表:
a = [0,1,2,3,4,5,6,7,8,9]
将此列表拆分为与每个其他元素对应的2个列表:
b = [0,2,4,6,8]
c = [1,3,5,7,9]
答案 0 :(得分:16)
你想:
b = a[::2] # Start at first element, then every other.
和
c = a[1::2] # Start at second element, then every other.
所以现在我们有了我们想要的东西:
>>> print(b)
[0, 2, 4, 6, 8]
>>> print(c)
[1, 3, 5, 7, 9]
答案 1 :(得分:4)
你可以使用列表切片来做到这一点:
b = a[::2]
c = a[1::2]
>>> a = [0,1,2,3,4,5,6,7,8,9]
>>> b = a[::2]
>>> c = a[1::2]
>>> print b
[0,2,4,6,8]
>>> print c
[1,3,5,7,9]
[::]
语法如下:[start:end:step]
。如果您没有为开始和结束指定任何参数,它将适用于整个列表。因此,上面的代码是:
对于b
:从索引0开始,从a
中取出所有其他元素
对于c
:从索引1开始,从a
答案 2 :(得分:1)
试试这个:
a = [0,1,2,3,4,5,6,7,8,9]
>>> b=[i for x,i in enumerate(a) if x%2==1]
>>> c=[i for x,i in enumerate(a) if x%2==0]
>>> b
[1, 3, 5, 7, 9]
>>> c
[0, 2, 4, 6, 8]