【问题标题】:What is the equivalent of array_column in python3python3中array_column的等价物是什么
【发布时间】:2018-05-22 06:36:05
【问题描述】:

我有一个字典列表,我只想从每个字典中获取特定项目。我的数据模式是:

data = [
    {
        "_id": "uuid",
        "_index": "my_index",
        "_score": 1,
        "_source": {
            "id" : 1,
            "price": 100
        }
    },
    {
        "_id": "uuid",
        "_index": "my_index",
        "_score": 1,
        "_source": {
            "id" : 2,
            "price": 150
        }
    },
    {
        "_id": "uuid",
        "_index": "my_index",
        "_score": 1,
        "_source": {
            "id" : 3,
            "price": 90
        }
    }
]

我想要的输出:

formatted_data = [
    {
        "id": 1,
        "price": 100
    },
    {
        "id": 2,
        "price": 150
    },
    {
        "id": 3,
        "price": 90
    }
]

为了形成数据,我使用了迭代 (for) 之类的

formatted_data = []
for item in data:
    formatted_data.append(item['_source'])

在 PHP 中,我可以使用 array_column() 代替 for 循环。那么在我的情况下,python3 中for 的替代方案是什么? 提前致谢。

【问题讨论】:

    标签: python python-3.x array-column


    【解决方案1】:

    您可以使用列表推导:

    In [11]: [e['_source'] for e in data]
    Out[11]: [{'id': 1, 'price': 100}, {'id': 2, 'price': 150}, {'id': 3, 'price': 90}]
    

    【讨论】:

      猜你喜欢
      • 2021-09-15
      • 2019-05-31
      • 2014-05-08
      • 2021-08-06
      • 2014-06-12
      • 1970-01-01
      • 2022-11-28
      • 2021-06-19
      • 2012-07-20
      相关资源
      最近更新 更多