簡體   English   中英

如何在python中切片元組列表?

[英]How to slice a list of tuples in python?

假設:

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

如何獲取每個tuple的索引0作為假裝結果:

[0, 1, 2]

為了得到這個,我使用了python list comprehension並解決了這個問題:

[num[0] for num in L]

盡管如此,它必須是一種L[:1]那樣切片的pythonic方式,但當然這種切片不起作用。

有更好的解決方案嗎?

您可以使用*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

但是你的已經完全沒問題了。

您可以將其轉換為 numpy 數組。

import numpy as np
L = [(0,'a'), (1,'b'), (2,'c')]
a = np.array(L)
a[:,0]

你的解決方案在我看來是最 Pythonic 的; 你也可以這樣做

tuples = [(0,'a'), (1,'b'), (2,'c')]
print zip(*tuples)[0]

...但對我來說這太“聰明”了,列表理解版本更清晰。

>>> list = [(0,'a'), (1,'b'), (2,'c')]
>>> l = []
>>> for t in list:
        l.append(t[0])

map呢?

map(lambda (number, letter): number, L)

在 python 2 中切片

map(lambda (number, letter): number, L)[x:y]

在python 3中,您必須先將其轉換為列表:

list(map(lambda (number, letter): number, L))[x:y]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM