1. 程式人生 > >字典巢狀列表獲取每個字典的值(values)

字典巢狀列表獲取每個字典的值(values)

方法一:

x=[{'close': '0.1021',                     'datetime': '2018-10-12 15:21:00',                     'high': '0.1021',                     'low': '0.1021',                     'open': '0.1021',                     'time': '1539328860000',                     'volume': '1643.3757'},                    {'close': '0.1021',                     'datetime': '2018-10-12 15:20:00',                     'high': '0.1021',                     'low': '0.1021',                     'open': '0.1021',                     'time': '1539328800000',                     'volume': '4232.6447'},                    {'close': '0.1019',                     'datetime': '2018-10-12 15:18:00',                     'high': '0.1019',                     'low': '0.1019',                     'open': '0.1019',                     'time': '1539328680000',                     'volume': '2909.9173'},]

首先判斷x的長度

num_ohlcvs=len(x)

建立一個空列表

result=[]

i=0

設定條件<這個長度

while i < num_ohlcvs:        長度下標遍歷的資料

       on3=x[i]

       獲取遍歷字典的值,強制轉換

       on4=list(on3.values())

       i=i+1

      新增到空的列表中

     result.append(on4)

print(result)     

[['1539328860000',   '0.1021',   '0.1021',   '0.1021',   '0.1021',   '1643.3757',   '2018-10-12 15:21:00'],  ['1539328800000',   '0.1021',   '0.1021',   '0.1021',   '0.1021',   '4232.6447',   '2018-10-12 15:20:00'],  ['1539328680000',   '0.1019',   '0.1019',   '0.1019',   '0.1019',   '2909.9173',   '2018-10-12 15:18:00']]

方法二

list=[]

for it  in x:

    for key in it:

         list.append(it[key])

n=7

on2=[list [i:i+n] for i in range(0,len(list),  n) ]

print(on2) 

兩個效果一樣