【问题标题】:Appending part of a string to a dictionary将字符串的一部分附加到字典
【发布时间】:2013-11-17 07:24:34
【问题描述】:

假设我有一个清单,项目:['a01:01-24-2011:s1', 'a03:01-24-2011:s2', 'a02:01-24-2011:s2'] 每个条目的结构为 [animalID:datevisited:stationvisited],并希望计算访问站的次数,我该怎么做? 只有两个s 所以如果我把它分成两个计数函数那就不麻烦了 我试过了

def counts_station:
   for item in items:
   counts={}
   if item[-2] in counts:
    counts[item[-2]]=counts[item[-2]]+1
   else:
    counts[item[-2]]=1
   returns counts

还有

def counts_station:
   for item in items:
    station=item[-2]
    if station in counts:
         counts[station]=counts[station]+1
    else:
         counts[station] = 1
    returns counts

帮助!?

【问题讨论】:

  • 你可以使用内置的collections.Counter库。
  • 另外,你好像做错了,-2不应该只是2吗?!

标签: python-3.x dictionary


【解决方案1】:

在尝试将字符串用作键之前,您需要将字符串拆分为子项,使用范围[-2:] 而不仅仅是-2,或者只取字符串的最后一个字符(1 或 2),不是倒数第二个。您的代码中还有一些小错误:需要将 counts 初始化为空字典:

items = ['a01:01-24-2011:s1', 'a03:01-24-2011:s2', 'a02:01-24-2011:s2']

def counts_station(items):
    counts={}
    for item in items:
        station=item[-1]
        if station in counts:
            counts[station]=counts[station]+1
        else:
            counts[station] = 1
    return counts

另一种方法是使用.get() 和默认值0,如果键不存在则返回:

def counts_station(items):
    counts={}
    for item in items:
        station=item[-1]
        counts[station]=counts.get(station,0) + 1
    return counts

【讨论】:

  • 谢谢:) 这很有帮助
猜你喜欢
  • 2017-06-06
  • 2014-07-05
  • 1970-01-01
  • 2023-02-24
  • 2018-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-28
相关资源
最近更新 更多