簡體   English   中英

從 Python 字典中獲取鍵和值作為列表

[英]get keys and values from a Python dictionary as lists

從我在 Python 上運行的代碼中,我得到了以下 output:

T1 =  [{0: 0}, {15: 3}, {19: 1}, {20: 1}, {0: 0}]

我想分別從每個 object 中提取鍵和值。 對於 T1,我將因此擁有:

P1 =  [0,15,19,20,0]
D1 = [0, 3, 1,1,0]

最好的編碼方式是什么?

提前致謝,

聽起來很適合chain.from_iterable

>>> from itertools import chain
>>> from operator import methodcaller

>>> T1 =  [{0: 0}, {15: 3}, {19: 1}, {20: 1}, {0: 0}]

>>> list(chain.from_iterable(T1))
[0, 15, 19, 20, 0]

>>> list(chain.from_iterable(map(methodcaller('values'), T1)))
[0, 3, 1, 1, 0]

字典在迭代時產生它的鍵; chain.from_iterable獲取此類可迭代對象的列表,並按順序生成它們的所有鍵。 要對值執行相同的操作,請在每個項目上調用values() ,為此我們在此處map調用者(相當於 ( methodcaller (i.values() for i in T1) )。

這應該工作:

T1 = [{0: 0}, {15: 3}, {19: 1}, {20: 1}, {0: 0}]

P1 = [next(iter(dct)) for dct in T1]
D1 = [next(iter(dct.values())) for dct in T1]

您將迭代器的第一個元素 ( next ) 放在鍵上 ( iter(dct) ) 或將插入器放在值上 ( iter(dct.values() )。

這不會創建任何不必要的列表。

或在一個 go 中(注意:這些返回tuples不是lists ):

P1, D1 = zip(*(next(iter(dct.items())) for dct in T1))

或(使用deceze 的部分答案):

from itertools import chain

P1, D1 = zip(*chain.from_iterable(dct.items() for dct in T1))

使用List Comprehensions

In [148]: P1 = [list(i.keys())[0] for i in T1]

In [149]: D1 = [list(i.values())[0] for i in T1]

In [150]: P1
Out[150]: [0, 15, 19, 20, 0]

In [151]: D1
Out[151]: [0, 3, 1, 1, 0]

暫無
暫無

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

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