如何在用户定义的函数中将列表作为参数传递?

时间:2019-04-07 18:01:23

标签: python-3.x

如何在函数中将列表作为参数传递?

我正在尝试形成一个名为“ get_all_latitude”的用户定义函数,该函数将根据数据集中的列表ID提取纬度。数据集的摘要(是词典列表)如下:

{
    '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'
}

这是我到目前为止的进展:

def get_all_latitude(data, list_id):
    new_list = []
    for row in data:
         if row['listing_id'] == list_id:
                new_list.append(row['latitude'])
                return new_list

如果我只有1个列表ID作为第二个参数(例如get_all_latitude(airbnb_data, '1133718'),这是可行的,但我想知道如何使其与列表(例如get_all_latitude(airbnb_data, ['10350448','13507262','13642646']))一起使用,因为我没有知道如何以一种可以解压缩列表元素的方式对其进行编码。

1 个答案:

答案 0 :(得分:0)

尝试一下:

def get_all_latitude(data, list_id):
    new_list = []
    for row in data:
        if row['listing_id'] in list_id:
            new_list.append(row['latitude'])
            return new_list

或者如果您想为所有列表ID定义列表:

def get_all_latitude(data, list_ids):
    new_lists = {list_id:list() for list_id in list_ids}
    for row in data:
         if row['listing_id'] == list_id:
            new_list[row['listing_id']].append(row['latitude'])
    return new_lists