【问题标题】:Python list help (incrementing count, appending)Python 列表帮助(递增计数,追加)
【发布时间】:2013-04-16 20:09:35
【问题描述】:

我正在尝试连接 google 的 geocode api 和 github api 来解析用户的位置并从中创建一个列表。

我要创建的数组(列表)是这样的:

location, lat, lon, count
San Francisco, x, y, 4
Mumbai, x1, y1, 5

位置、纬度和经度是从 Google 地理编码中解析出来的,计数是该位置的出现次数。每次添加新位置时:如果它存在于列表中,则计数增加,否则将其附加到具有位置、纬度、经度的数组(列表)中,并且计数应为 1。

另一个例子:

location, lat, lon, count
Miami x2, y2, 1 #first occurrence
San Francisco, x, y, 4 #occurred 4 times already
Mumbai, x1, y1, 5 #occurred 5 times already
Cairo, x3, y3, 1 #first occurrence

我已经可以从 github 获取用户的位置,并且可以从 google 获取地理编码数据。我只需要在我正在努力解决的 python 中创建这个数组。

谁能帮助我?谢谢。

【问题讨论】:

  • 我建议改用字典 (dict)。
  • 如果您想要使用 csv 模块打印的列表,请查看 this 答案以了解使用 dict 执行此操作的方法。
  • 纬度/经度是否与位置直接相关,例如,所有旧金山位置是否都具有相同的纬度/经度?如果没有,您将需要额外的结构来保持数据完整。

标签: python arrays list


【解决方案1】:

这是所有其他推荐想法的融合:

from collections import defaultdict

inputdata = [('Miami', 'x2', 'y2'),
             ('San Francisco', 'x', 'y'),
             ('San Francisco', 'x4', 'y4'),
             ('Mumbai', 'x1', 'y1'),
             ('Cairo', 'x3', 'y3')]

counts, coords = defaultdict(int), defaultdict(list)

for location, lat, lon in inputdata:
    coords[location].append((lat,lon))
    counts[location] += 1

print counts, coords

这使用了 defaultdict,正如您所见,它可以轻松实现两者:

  1. 按城市统计出现次数
  2. 保持纬度/经度对完整

返回:

defaultdict(<type 'int'>, {'Miami': 1, 'San Francisco': 2, 'Cairo': 1, 'Mumbai': 1}) 
defaultdict(<type 'list'>, {'Miami': [('x2', 'y2')], 'San Francisco': [('x', 'y'), ('x4', 'y4')], 'Cairo': [('x3', 'y3')], 'Mumbai': [('x1', 'y1')]})

这个答案做了一个(未经验证的)假设,即您的纬度/经度对的粒度不太可能重复,但实际上您只对按城市进行计数感兴趣。

【讨论】:

    【解决方案2】:

    Python 有一个专门用于计算事物发生次数的预烘焙类:它称为collections.Counter。如果您可以生成一个迭代器,该迭代器从您的输入数据中给出连续的元组(city, lat, lon)(可能使用生成器表达式),只需将其传递给Counter 即可直接为您提供所需的内容。例如,

    >>> locations = [('Miami', 1, 1), ('San Francisco', 2, 2), ('Mumbai', 3, 3), ('Miami', 1, 1), ('Miami', 1, 1)]
    >>> Counter(locations)
    Counter({('Miami', 1, 1): 3, ('San Francisco', 2, 2): 1, ('Mumbai', 3, 3): 1})
    

    如果您需要能够在程序运行时添加更多位置而不是批处理,请将相关元组放入该计数器的 update 方法中。

    【讨论】:

      【解决方案3】:

      使用collections.Counter,您可以这样做:

      from collections import Counter
      
      # initial values
      c=Counter({("Mumbai", 1, 2):5, ("San Francisco", 3,4): 4})
      
      #adding entries
      c.update([('Mumbai', 1, 2)])
      print c  # Counter({('Mumbai', 1, 2): 6, ('San Francisco', 3, 4): 4})
      
      c.update([('Mumbai', 1, 2), ("San Diego", 5,6)])
      print c  #Counter({('Mumbai', 1, 2): 7, ('San Francisco', 3, 4): 4, ('San Diego', 5, 6): 1})
      

      【讨论】:

      • 对于 single 条目 .update() 相当冗长。您也可以直接添加到柜台:c['Mumbai', 1, 2] += 1.
      • 感谢 Martijn,这更干净了!
      【解决方案4】:

      使用 python dict 怎么样?你可以在这里阅读它们

      http://docs.python.org/2/tutorial/datastructures.html#dictionaries

      这是一个示例实现:

      // Create an empty dictionary.
      dat = {}
      
      if dat.has_key(location):
          dat[location] = dat[location] + 1
      else:
          dat[location] = 1
      

      【讨论】:

        【解决方案5】:

        这将更好地存储为字典,按城市名称索引。您可以将其存储为两个字典,一个用于纬度/经度的元组字典(因为 lat/long 永远不会改变):

        lat_long_dict = {}
        lat_long_dict["San Francisco"] = (x, y)
        lat_long_dict["Mumbai"] = (x1, y1)
        

        还有一个 collections.defaultdict 用于计数,所以它总是从 0 开始:

        import collections
        city_counts = collections.defaultdict(int)
        
        city_counts["San Francisco"] += 1
        city_counts["Mumbai"] += 1
        city_counts["San Francisco"] += 1
        # city counts would be
        # defaultdict(<type 'int'>, {'San Francisco': 2, 'Mumbai': 1})
        

        【讨论】:

        • 我如何将 lat 和 lon 添加到这个字典中?
        • 也许我做错了什么。我的输出是 test: {u'San Francisco, CA, USA': '-122.4194155, 37.7749295'} - defaultdict(, {u'San Francisco, CA, USA': 1}); #count 应该是 4。
        • 最好将 lat 和 long 包含在 key 中(以区分 Paris, France 和 Paris, Texas...),因此应该使用元组 (city, lat, long) 作为 key
        • 一个 collections.Counter 会比一个 defaultdict 更好,它是专门为......计数而设计的! :-) 另外,@ThierryLathuille 所说的。
        • @ThierryLathuille 我喜欢你所说的,但我只是不知道如何在 python 中做到这一点。你能引导我到一个网址或更新你的答案吗?谢谢。
        猜你喜欢
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 2020-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-25
        相关资源
        最近更新 更多