python - 如何在 python 中切片元组列表?

标签 python list python-2.7 list-comprehension slice

假设:

L = [(0,'a'), (1,'b'), (2,'c')]

如何获取每个元组的索引0作为假装结果:

[0, 1, 2]

为此,我使用了 python list comprehension 并解决了问题:

[num[0] for num in L]

不过,它一定是一种 pythonic 方式来 L[:1] 那样切片,但是当然这种切片不起作用。

有没有更好的解决方案?

最佳答案

您可以使用 *zip() 解包。

>>> l = [(0,'a'), (1,'b'), (2,'c')]
>>> for item in zip(*l)[0]:
...     print item,
...
0 1 2

对于 Python 3,zip() 不会自动生成 list,因此您要么必须将 zip 对象发送到list() 或使用 next(iter()) 或其他东西:

>>> l = [(0,'a'), (1,'b'), (2,'c')]
>>> print(*next(iter(zip(*l))))
0 1 2

但是你的已经很好了。

关于python - 如何在 python 中切片元组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33829535/

相关文章:

python - 凯拉斯图像数据生成器 : why are the outputs of my CNN reversed?

Python将列表转换为具有键值的字典

python - Python 中 TwitterAPI 包中的多个搜索词

c++ - 我在一些指针上遇到了问题,调试结束时访问位置失败

java - 尝试在 Java 列表上进行 stream().filter().collect(Collectors.toList())) 时获取 NullPointerException

python - 通过 python 程序将参数传递给 Cygwin

Python Selenium 返回文本,unicode 对象不可调用

Python:迭代具有不同维数的列表,有通用的方法吗?

python - 当一个键过期时,set_response_callback 不调用回调方法

list - 在 r 中,如何从去除 NA 的矩阵创建列表?