"How can I create a function that outputs the latitude when I input the listing_id for the given data?"

2024-04-25 21:42:18 发布

您现在位置:Python中文网/ 问答频道 /正文

这是更大的数据集的一部分,但如果代码工作,我相信我可以将它应用到整个数据集。这是我正在处理的数据示例。你知道吗

data = [
    {
        'listing_id': '1133718',
        'survey_id': '1280',
        'host_id': '6219420',
        'room_type': 'Shared room',
        'country': '',
        'city': 'Singapore',
        'borough': '',
        'neighborhood': 'MK03',
        'reviews': 9.0,
        'overall_satisfaction': 4.5,
        'accommodates': '12',
        'bedrooms': '1.0',
        'bathrooms': '',
        'price': 74.0,
        'minstay': '',
        'last_modified': '2017-05-17 09:10:25.431659',
        'latitude': 1.293354,
        'longitude': 103.769226,
        'location': '0101000020E6100000E84EB0FF3AF159409C69C2F693B1F43F'
    },
    {
        'listing_id': '1196810',
        'survey_id': '1280',
        'host_id': '6236420',
        'room_type': 'Shared room',
        'country': '',
        'city': 'Singapore',
        'borough': '',
        'neighborhood': 'MK11',
        'reviews': 9.0,
        'overall_satisfaction': 3.5,
        'accommodates': '11',
        'bedrooms': '2.0',
        'bathrooms': '',
        'price': 84.0,
        'minstay': '',
        'last_modified': '2017-05-17 09:10:25.431659',
        'latitude': 1.34567,
        'longitude': 103.769226,
        'location': '0101000020E6100000E84EB0FF3AF159409C69C2F693B1F43F'
    }
    .
    .
    .
    ]

如果函数起作用,我想触发一个函数,如:

get_all_latitude(data, ['1196810', '1133718'])

对于预期输出:

 [1.34567, 1.293354]

Tags: 数据idhostcitydatatypecountrysurvey
2条回答

与其每次都搜索,只需将其存储在dict中的键值对(listing_idlatitude)中,而使用for循环只需检索给定listing_id的纬度值并求解它

def get_all_latitude(data, list_of_data):
    dic = {i['listing_id']:i['latitude'] for i in data}
    return [ dic[i] for i in list_of_data ]   

list_of_data = ['1196810', '1133718']
print(get_all_latitude(data,list_of_data))

输出

[1.34567, 1.293354]

我会这样做:(假设'data'变量是一个列表,我假设这是您想要的。)

def get_all_latitude_data(data, ids):
    return [datum["latitude"] for datum in data if datum["listing_id"] in ids]

这将按预期进行。如果列表中没有列出ID的数据点,它将返回一个空列表。你知道吗

编辑-

根据您对问题的评论,如果有帮助的话,这个列表理解基本上是这样做的:

def get_all_latitude_data_loop(data, ids):
    output = []
    for datum in data:
        if datum["listing_id"] in ids:
            output.append(datum["latitude"])
    return output

记住,列表理解更像是“Python”,通常更快,但两者都有效。你知道吗

相关问题 更多 >