繁体   English   中英

Python - 生成器 object 转化为列表列表

[英]Python - Generator object into a list of lists

我有一个生成器 object 'results',它在循环时返回一个字典列表。 我正在尝试将其转换为列表列表,因此我可以轻松地遍历并引用要插入到数据库中的每个值。 我相信我遇到了麻烦,因为这是一个发电机 object,我该怎么做?

如:

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'], ... ]

我在这里做错了什么?

看起来你正试图得到这个:

[list(r.keys()) for r in results]

话虽这么说,可能有更好的方法来做你正在做的事情; 你能解释一下你打算如何插入这些项目吗? 或者你想要列表中的值:

[list(r.values()) for r in results]

但实际上,看起来您正在处理这里的结构化数据,这意味着您应该将其添加到 pandas dataframe 并根据需要过滤行或选择列。 您需要做的就是:

import pandas as pd
df = pd.DataFrame(results)

您可以阅读 pandas 文档,了解如何对数据进行操作并获取您想要的表格。 它还将使最终加载到您的 SQL 数据库变得更加容易。

代替

iList = list(r_id + r_name ...)

iList = [r_id, r_name, ...]

r_id + r_name...通过连接所有 arguments 创建一个大字符串, list() function 创建字符串中所有字符的列表。 你不想要那个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM