2017-10-11 80 views
0

我使用Python和具有以下詞典的陣列中的特定索引:訪問在陣列(Python)的

{ 
    'Measurement1': { 
     'point1': [['1.1', '1,2', '497.1937349917', '497.1937349917', '497.1937349917'], 
        ['3.1', '1,2', '497.6760940676', '497.6760940676', '497.6760940676'], 
        ['1.1', '3,4', '495.0455154634', '495.0455154634', '495.0455154634'], 
        ['3.1', '3,4', '497.003633083', '497.003633083', '497.003633083']] 
    } 
} 

我試圖從數據[「測量1」] [」得到的所有元素point1'] [all_data_sets] [2]稍後在程序中做一個','。join()來進行額外的計算。我希望能得到這樣的輸出:

'497.1937349917', '495.0455154634', '500.9453006597', '490.1952705428' 

我目前正在循環訪問數組。

value_temp = [] 
for data_elem in data['Measurement1']['point1']: 
    value_temp.append(data_elem[2]) 

output = ','.join(value_temp) 

有沒有辦法抓住這些值而不執行循環?

+0

你忘了問一個問題 –

+0

這實際上更多的是話題https://codereview.stackexchange.com/ –

+1

您可能會看到稍微增加速度,列表理解'output =','。join([data_elem [2] for data_elem in data ['Measurement1'] ['point1']])''。你不能爲此打敗'O(n)'(想想這樣:把每個元素寫入字符串,你必須看看它,沒有辦法「跳過元素」)。 –

回答

1

如果您想要更高效的方法,您應該使用numpy爲您的整個項目。

只要把你的代碼片段爲例:

import numpy as np 

# suppose your dict named "data" 

data["Measurement1"]["point1"] = np.array(data["Measurement1"]["point1"]) 

output = ",".join(data["Measurement1"]["point1"][:, 2]) 

索引和計算在numpyC完成的,所以它是真的要快得多。

1

我認爲你是列表理解之後(其本質上仍是循環通過,但在一個更Python的方式):

",".join([data_elem[2] for data_elem in data['Measurement1']['point1']]) 

雖然輸出值不匹配,什麼是真正的在您的文章。如果這不是你想要的,請澄清值應該來自哪裏...

0

嘗試使用地圖功能。

output = ",".join(map(lambda arr: arr[2],data['Measurement1']['point1'])) 
0

鑑於你原來的dict(字典(名單(名單()))),

x = { 
    'Measurement1': { 
    'point1': [['1.1', '1,2', '497.1937349917', '497.1937349917', '497.1937349917'], 
       ['3.1', '1,2', '497.6760940676', '497.6760940676', '497.6760940676'], 
       ['1.1', '3,4', '495.0455154634', '495.0455154634', '495.0455154634'], 
       ['3.1', '3,4', '497.003633083', '497.003633083', '497.003633083']] 
    } 
} 

注意X [ '測量1'] [ '點1'] [2]是序數第3(子)數組元素。你可以這樣打印此引用,

print (x['Measurement1']['point1'][2]) 

,你可以直接分配,使用列表理解來參照,或者乾脆加入該(子)數組中的元素,

#use the (sub)array reference directly 
','.join(x['Measurement1']['point1'][2]) 
#or compose a new array using list comprehension 
','.join([ z for z in x['Measurement1']['point1'][2] ]) 
#or assign array reference to variable 
y = x['Measurement1']['point1'][2] 
','.join(y) 

您也可以副本(避免原廠原裝的意外修改,

#duplicate via list comprehension, 
y = [ z for z in x['Measurement1']['point1'][2] ] 
#copy the reference using list() 
y = list(x['Measurement1']['point1'][2]) 
#or copy.copy() #import copy 
y = copy.copy(x['Measurement1']['point1'][2]) 
#then 
','.join(y)