Python 带有位置列表的标记对象
有一个名为Python 带有位置列表的标记对象,python,python-3.x,Python,Python 3.x,有一个名为cleaned_trips的对象,它是一个行程列表,它的dict有trip_distance,picku latitude,picku longitude等键。现在,从该列表中仅获取键拾取纬度和拾取经度,并以[拾取经度,拾取经度]格式返回标记对象及其位置。这是我尝试过的,但始终附加相同的位置 cleaned_trips = [{'trip_distance': 18.38, 'pickup_latitude': 40.64499,
cleaned_trips
的对象,它是一个行程列表,它的dict有trip_distance
,picku latitude
,picku longitude
等键。现在,从该列表中仅获取键拾取纬度
和拾取经度
,并以[拾取经度,拾取经度]
格式返回标记对象及其位置。这是我尝试过的,但始终附加相同的位置
cleaned_trips = [{'trip_distance': 18.38,
'pickup_latitude': 40.64499,
'pickup_longitude': -73.78115},
{'trip_distance': 1.3,
'pickup_latitude': 40.766931,
'pickup_longitude': -73.982098},
{'trip_distance': 4.5,
'pickup_latitude': 40.77773,
'pickup_longitude': -73.951902},
{'trip_distance': 2.4,
'pickup_latitude': 40.795678,
'pickup_longitude': -73.971049}]
def location(trip):
latlng = [trip['pickup_latitude'], trip['pickup_longitude']]
return latlng
def markers_from_trips(trips):
new_list = []
marker = {}
for trip in trips:
for key in trip:
marker['location'] = location(trip)
new_list.append(marker)
return new_list
trip_markers = markers_from_trips(cleaned_trips)
print(trip_markers)
print(len(trip_markers))
marker.location
的输出应该是这样的
# [[40.64499, -73.78115],
# [40.766931, -73.982098],
# [40.77773, -73.951902],
# [40.795678, -73.971049]]
这是演示列表理解在这里是完美的:
>>> [[trip["pickup_latitude"], trip["pickup_longitude"]] for trip in cleaned_trips]
[[40.64499, -73.78115], [40.766931, -73.982098], [40.77773, -73.951902], [40.795678, -73.971049]]
您看到同一位置被追加了12次,因为您只创建了一次标记
(在读取marker={}
的行上),然后在循环中多次追加它。要每次将新词典附加到列表中,请确保在每个循环中创建一个新词典:
def markers_from_trips(trips):
new_list = []
for trip in trips:
marker = {"location": [trip["pickup_latitude"], trip["pickup_longitude"]]}
new_list.append(marker)
return new_list
或者,再次使用列表:
>>> [{"location": [trip["pickup_latitude"], trip["pickup_longitude"]]} for trip in cleaned_trips]
[{'location': [40.64499, -73.78115]}, {'location': [40.766931, -73.982098]}, {'location': [40.77773, -73.951902]}, {'location': [40.795678, -73.971049]}]
谢谢你的解决方案。只是想澄清一下“要在每次列表中添加一个新字典,请确保在每个循环中创建一个新字典:”。这意味着我应该在trips:语句中的trip的
之后加上marker={}
?好的,您可以命名“marker”对象,然后在两个单独的步骤中追加,如果您觉得更清楚的话。更新了我上面的答案以说明这一点。问题是我使用了嵌套循环,因此我无法确定在何处初始化空标记dict。我在理解循环中的附加部分时遇到了问题。