有一个名为cleaned_trips
的对象,它是一个行程列表,它的字典具有诸如trip_distance
,pickup_latitude
,pickup_longitude
之类的键。现在,从此列表中仅获得键pickup_latitude
和pickup_longitude
,并返回标记对象,其位置格式为[pickup_latitude, pickup_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]]
答案 0 :(得分:1)
列表理解在这里很完美:
>>> [[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
(在读取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]}]