【问题标题】:How do I include part of my code into 'yield'?如何将部分代码包含到“产量”中?
【发布时间】:2021-10-17 06:11:13
【问题描述】:

感谢您的宝贵时间!

每个产品,有时都有多个型号。我通过 for 循环获得了单个产品中各个型号的型号“名称”和“价格”。

但是,我如何将这些详细信息与同一产品的其他变量一起“转移”到“产量”部分?以下是我的尝试,但我没有得到正确的结果。如何编辑代码,以便它可以在同一产品中记录多个型号(以及价格)(如果适用):

    for i in resp['item']['models']:
        if i['name'] is not None:
            model = i['name']
            model_pricing = i['price']


    yield{
        'product': resp.get('item').get('name'),
        'rating': resp.get('item').get('item_rating').get('rating_star'),
        'review numbers': resp.get('item').get('cmt_count'),
        'viewcount': resp.get('item').get('view_count'),
        'likes': resp.get('item').get('liked_count'),
        'model_pricing': model_pricing,
        'model': model,
        'location': resp.get('item').get('shop_location')
        }

【问题讨论】:

  • 您不应将模型属性拆分为两个单独的列表(名称和价格)。原始数据结构比您尝试创建的更好。
  • @trincot,所以,我应该使用在每个模型的循环中包含产量?
  • 这里代码的缩进和你原来的代码一样吗?这里的 yield 不是循环的一部分,而您可能是故意的。
  • 其他一些在这里非常有用的东西:一些示例输入的示例、当前(不正确的)输出以及该输入的预期(期望)输出。

标签: python scrapy nested-loops yield


【解决方案1】:

你应该将你的产量保持在 for 循环和 if 语句中。 你可以尝试如下:

for i in resp['item']['models']:
    if i['name'] is not None:
        model = i['name']
        model_pricing = i['price']

        yield {
            'product': resp.get('item').get('name'),
            'rating': resp.get('item').get('item_rating').get('rating_star'),
            'review numbers': resp.get('item').get('cmt_count'),
            'viewcount': resp.get('item').get('view_count'),
            'likes': resp.get('item').get('liked_count'),
            'model_pricing': model_pricing,
            'model': model,
            'location': resp.get('item').get('shop_location')
            }

【讨论】:

    【解决方案2】:

    您不应将模型属性拆分为两个单独的列表(名称和价格)。原始数据结构比您尝试创建的更好。

    你应该在你的 yield 字典中创建一个 models 属性(我建议使用复数),并让它成为一个包含名称/价格对的列表。这些对可以是元组——也可以是其他一些数据结构(自定义类实例、命名元组、字典...):

    yield {
        # ... other attributes ...
        'models': [(model['name'], model['price']) for model in resp['item']['models']],
    }
    

    【讨论】:

    • tq!有效!我学到了一些新东西并纠正了我的错误。然而,我更喜欢@fazlul 下面的方法。不过非常感谢!我很感激
    • 好的。只是重复一遍,将关于(模型)对象的属性分隔在两个列表中是不好的做法,当它们位于相同的索引时,它们是相关的。 OOP 意味着您将属于一起的东西放在一起(型号名称和价格)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 2018-04-28
    • 2018-07-15
    • 1970-01-01
    • 2018-04-03
    • 2019-01-04
    相关资源
    最近更新 更多