访问数组数组中的特定索引(Python)

时间:2017-10-11 01:12:54

标签: python arrays

我使用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']]
    }
}

我正在尝试从数据中获取所有元素[' Measurement1'] [' point1'] [ all_data_sets ] [2]以执行& #39;,' .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)   

有没有办法在不执行循环的情况下获取这些值?

4 个答案:

答案 0 :(得分:1)

我认为你是在列表理解之后(它仍然基本上循环,但是以更加pythonic的方式):

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

虽然输出值与帖子中的实际值不匹配。如果这不是你想要的,请说明价值应来自哪里......

答案 1 :(得分: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])

numpy中的索引编制和计算由C完成,所以速度确实快得多。

答案 2 :(得分:0)

尝试使用地图功能。

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

答案 3 :(得分:0)

鉴于你的原始字典(dict(list(list()))),

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 [' Measurement1'] [' point1'] [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 )