获取Python

时间:2017-06-04 03:36:19

标签: python arraylist

我有以下字符串列表:

"ID":[[310.5,1.1612828],[310.0,15.0],[310.0,2.9755309],[309.5,30.0]]

我想将每个列表的所有第一个值都抓取到variable,因此输出应该是这种情况

print variable

预期产出:

310.5
310.0
310.0
309.5

3 个答案:

答案 0 :(得分:3)

id = [[310.5,1.1612828],[310.0,15.0],[310.0,2.9755309],[309.5,30.0]]

# If you just want to output to console:
[print(x[0]) for x in id]  #if id a list
# if id is in dict named dict_
[print(x[0] for x in dict_['id']

这是一个更长的版本。

dict_ = {'id': [[310.5,1.1612828],
                [310.0,15.0],
                [310.0,2.9755309],
                [309.5,30.0]]
                }



#make a list containing position 0 values of sublists
pos_0 = [x[0] for x in dict_['id']]
print(pos_0)

#output them to a file
for entry in pos_0:
      print(entry)

答案 1 :(得分:1)

要将第一个元素捕获到变量中,您可以使用list comprehension之类的:

代码:

data = {
    'ID': [[310.5, 1.1612828],
           [310.0, 15.0],
           [310.0, 2.9755309],
           [309.5, 30.0]]
}

variable = [x[0] for x in data['ID']]

print(variable)

结果:

[310.5, 310.0, 310.0, 309.5]

答案 2 :(得分:0)

此代码将迭代每个第一个元素并将其附加到out列表,以便将来访问。

dict_ = {"ID":[[310.5,1.1612828],[310.0,15.0],[310.0,2.9755309],[309.5,30.0]]}
out=[]

for item in dict_["ID"]:
    out.append(item[0])
print(out)

这将输出[310.5, 310.0, 310.0, 309.5]。这是你需要的吗?