[英]Possible to extract a List from a Dictionary of Lists in Python?
我知道使用.values()會將值從字典中拉出到列表中,但是我很好奇是否有可能將第二個項目(例如)從字典中的列表中拉出而沒有循環。
例如:
dictionary1={
fish : [1, 2, 3],
dog : [9, 5, 8],
cat : [4, 4, 4]
}
我想提取列表:
[3, 8, 4]
只是好奇是否有比循環更干凈的方法,謝謝!
應該這樣做:
>>> [v[2] for v in dictionary1.values()]
[3, 8, 4]
您應該將關鍵字放在字典的單引號/雙引號中。
d1 = {
"fish" : [1, 2, 3],
"dog" : [9, 5, 8],
"cat" : [4, 4, 4]
}
print [x[-1] for x in d1.values()]
在您的問題中(如果我是對的話),您基本上是根據字典值創建2D數組,然后嘗試獲取該2D數組的特定列。 如果是這樣,您可以使用python軟件包numpy
輕松做到這一點,可以在此處找到該軟件包的文檔,
我認為以下代碼將幫助您入門,
import numpy
dictionary1=dict(
fish = [1, 2, 3],
dog = [9, 5, 8],
cat = [4, 4, 4]
)
numpy_array = numpy.array(dictionary1.values())
column_number = 2
print numpy_array[:,column_number]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.