【发布时间】:2021-02-25 03:04:55
【问题描述】:
我有一个生成器对象“结果”,它在循环时会返回一个字典列表。我正在尝试将其转换为列表列表,因此我可以轻松地循环并引用要插入到数据库中的每个值。我相信我遇到了麻烦,因为这是一个生成器对象,我该怎么做?
如:
def parse(results):
for r in results:
print(r)
结果:
[{'id': '7229957054', 'repost_of': None, 'name': '1996 Acura Integra', 'url': 'https://monterey.craigslist.org/cto/d/salinas-1996-acura-integra/7229957054.html', 'datetime': '2020-11-12 14:37', 'last_updated': '2020-11-12 14:37', 'price': '$1,000', 'where': 'Salinas', 'has_image': True, 'geotag': None, 'deleted': False}, {'id': '7229839309', 'repost_of': None, 'name': '1990 Acura Integra GS', 'url': 'https://monterey.craigslist.org/cto/d/salinas-1990-acura-integra-gs/7229839309.html', 'datetime': '2020-11-12 11:31', 'last_updated': '2020-11-12 11:31', 'price': '$2,800', 'where': 'Salinas, Ca', 'has_image': True, 'geotag': None, 'deleted': False}]
我的代码:
def initialParse(results):
rList = []
for r in results:
r_id = str(r['id'])
r_name = str(r['name'])
r_url = str(r['url'])
r_datetime = str(r['datetime'])
r_updated = str(r['last_updated'])
r_price = str(r['price'])
r_where = str(r['where'])
iList = list(r_id + r_name + r_url + r_datetime + r_updated + r_price + r_where)
rList.append(iList)
print(rList)
返回:
[['7', '2', '2', '9', '9', '5', '7', '0', '5', '4', '1', '9', '9', '6', ' ', 'A', 'c', 'u', 'r', 'a', ' ', 'I', 'n', 't', 'e', 'g', 'r', 'a', 'h', 't', 't', 'p', 's', ':', '/', '/', 'm', 'o', 'n', 't', 'e', 'r', 'e', 'y', '.', 'c', 'r', 'a', 'i', 'g', 's', 'l', 'i', 's', 't', '.', 'o', 'r', 'g', '/', 'c', 't', 'o', '/', 'd', '/', 's', 'a', 'l', 'i', 'n', 'a', 's', '-', '1', '9', '9', '6', '-', 'a', 'c', 'u', 'r', 'a', '-', 'i', 'n', 't', 'e', 'g', 'r', 'a', '/', '7', '2', '2', '9', '9', '5', '7', '0', '5', '4', '.', 'h', 't', 'm', 'l', '2', '0', '2', '0', '-', '1', '1', '-', '1', '2', ' ', '1', '4', ':', '3', '7', '2', '0', '2', '0', '-', '1', '1', '-', '1'...]
将 rList.append() 移出一个块会在包含所有条目的列表中给出一个列表...我需要列表中的每个结果 r 在它自己的列表中...像这样:
[['id', 'name', 'url', 'datetime', 'lastupdated', 'price', 'where'], ['id', 'name', 'url', 'datetime', 'lastupdated', 'price', 'where'], ... ]
我在这里做错了什么?
【问题讨论】:
-
问题是 iList = list(r_id + r_name + r_url + r_datetime + r_updated + r_price + r_where)。 iList 的更改 = [r_id + r_name + r_url + r_datetime + r_updated + r_price + r_where]
标签: python python-3.x list dictionary generator