【问题标题】:Filter python dictionary with dictionary-comprehension使用字典理解过滤 python 字典
【发布时间】:2018-04-07 13:04:06
【问题描述】:

我有一本真正的 geojson 字典:

points = {
    'crs': {'properties': {'name': 'urn:ogc:def:crs:OGC:1.3:CRS84'}, 'type': 'name'},
    'features': [
        {'geometry': {
            'coordinates':[[[-3.693162104185235, 40.40734504903418],
                            [-3.69320229317164, 40.40719570724241],
                            [-3.693227952841606, 40.40698546120488],
                            [-3.693677594635894, 40.40712700492216]]],
            'type': 'Polygon'},
         'properties': {
             'name': 'place1',
             'temp': 28},
         'type': 'Feature'
        },
        {'geometry': {
            'coordinates': [[[-3.703886381691941, 40.405197271972035],
                             [-3.702972834622821, 40.40506272989243],
                             [-3.702552994966045, 40.40506798079752],
                             [-3.700985024825222, 40.405500820623814]]],
            'type': 'Polygon'},
         'properties': {
             'name': 'place2',
             'temp': 27},
         'type': 'Feature'
        },
        {'geometry': {
            'coordinates': [[[-3.703886381691941, 40.405197271972035],
                             [-3.702972834622821, 40.40506272989243],
                             [-3.702552994966045, 40.40506798079752],
                             [-3.700985024825222, 40.405500820623814]]],
            'type': 'Polygon'},
         'properties': {
             'name': 'place',
             'temp': 25},
         'type': 'Feature'
        }
    ],
    'type': u'FeatureCollection'
}

我想对其进行过滤,使其仅停留在具有特定温度的地方,例如超过 25 摄氏度。

我已经设法做到了:

dict(crs = points["crs"],
     features = [i for i in points["features"] if i["properties"]["temp"] > 25],
     type = points["type"])

但我想知道是否有任何方法可以通过字典理解更直接地做到这一点。

非常感谢。

【问题讨论】:

  • 唯一更直接的方法是使用文字。为什么需要字典理解?
  • 你目前的方法一点也不差
  • 看看你的数据结构,我认为唯一改变的是特性列表——所以你已经拥有的,使用列表理解,看起来正是你需要的。
  • 您没有考虑过使用geopandas.org 并使用它进行过滤吗?
  • 非常感谢大家。我提出问题的原因是因为我有一个函数可以在更大的字典中多次执行此过滤器,我想知道是否有更有效的过滤方式。

标签: python dictionary list-comprehension dictionary-comprehension


【解决方案1】:

我来晚了。 dict compreheneison 不会帮助你,因为你只有三个键。但如果您满足以下条件: 1. 您不需要features 的副本(例如您的dict 是只读的); 2. 您不需要对features 的索引访问,您可以使用生成器推导而不是列表推导:

dict(crs = points["crs"],
                features = (i for i in points["features"] if i["properties"]["temp"] > 25),
                type = points["type"])

生成器是在恒定时间内创建的,而列表推导式是在 O(n) 中创建的。此外,如果你创建了很多这样的字典,你的内存中只有一个 features 的副本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-22
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2016-02-21
    • 2013-01-08
    • 1970-01-01
    相关资源
    最近更新 更多