python - 通过偶数和奇数索引将列表分成两半?

标签 python list split

Possible Duplicate:
Python program to split a list into two lists with alternating elements

我有一个这样的列表:

list1 = [blah, 3, haha, 2, pointer, 1, poop, fire]

我想要的输出是:

list = [3, 2, 1, fire]

所以我想要的是列出前一个列表的偶数元素。我尝试使用 for 语句并尝试删除第 2 个元素,同时将它们附加到列表中,但没有成功:

count = 0
for a in list1:
 list2.append(a)
 if count % 2 = = 1:
  list2.pop(count)

print list2

有什么建议吗?

最佳答案

您可以使用列表切片。下面的代码片段就可以了。

list1 = ['blah', 3, 'haha', 2, 'pointer', 1, 'poop', 'fire']
listOdd = list1[1::2] # Elements from list1 starting from 1 iterating by 2
listEven = list1[::2] # Elements from list1 starting from 0 iterating by 2
print listOdd
print listEven

输出

[3, 2, 1, 'fire']
['blah', 'haha', 'pointer', 'poop']

关于python - 通过偶数和奇数索引将列表分成两半?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11702414/

相关文章:

python - access(2) vs stat(2) 检查文件是否可执行

python - 过滤列表中的每个项目以检查它是否在 ID 列表中

Python2.7 argparse 需要一个或两个选项

list - 如何将函数仅映射到列表中的某些元素?

linux - 拆分和删除文件?

shell - Unix Shell 脚本 : Remove common prefix from a variable

python - 如何从Python中的数据帧的每一行获取列值

用于连接列表的 Python 列表理解(扁平化)

python - 为什么具有相同数据的列表具有不同的大小?

Javascript 正则表达式拆分拒绝 null