python中提取列表的奇数元素和偶数元素

 

>>> a = list(range(1,21)) ## 生成列表
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
>>> a[::2]  ## 提取第奇数元素
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> a[1::2]  ## 提取第偶数元素
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

 

>>> a = list(range(1,21))
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
>>> a[::-2]
[20, 18, 16, 14, 12, 10, 8, 6, 4, 2]
>>> a[-2::-2]
[19, 17, 15, 13, 11, 9, 7, 5, 3, 1]

 

posted @ 2021-02-23 22:22  小鲨鱼2018  阅读(7861)  评论(0编辑  收藏  举报