为列表或词典中的每个项添加一年

时间:2013-03-30 13:12:27

标签: python dictionary count add

这个问题可能微不足道。如何将从2009年结束的1903年开始添加到列表中的106个项目,而不创建长巨大年份列​​表 绕过一年?

例如:

  States : Boston Americans, World Series Not Played in 1904, New York,  
           Chicago, Chicago, Chicago
           Pittsburgh, Philadelphia, Philadelphia,
           Boston, Philadelphia, Boston, Boston,Boston]`

对此:

  States : [Boston Americans:1903], [World Series Not Played:1904], [New York:1905],  
           [Chicago:1906],[Chicago:1907:],[Chicago:1908]....ect

虽然我知道您可以为列表中的每个项目添加数字计数

 d = defaultdict(int)
 for word in words.split():
     d[word] += 1

我试过了:

 d = {}
 for i in new_list:
     d[1903 + i] += 1 # I know this looks crazy but this is all I have
     print(d)

我得到了

TypeError: 'function' object is not iterable

但这对我来说是新的。我通常会有更多展示,但我真的没有任何想法  如何编码这一点。

4 个答案:

答案 0 :(得分:4)

如果您有获奖者名单,例如:

>>> winners
['Boston Americans', 'World Series Not Played in 1904', 'New York', 'Chicago', 'Chicago', 'Chicago', 'Pittsburgh', 'Philadelphia', 'Philadelphia', 'Boston', 'Philadelphia', 'Boston', 'Boston', 'Boston']

您可以使用enumerate将这些与数字相关联:

>>> list(enumerate(winners, 1903))
[(1903, 'Boston Americans'), (1904, 'World Series Not Played in 1904'), (1905, 'New York'), (1906, 'Chicago'), (1907, 'Chicago'), (1908, 'Chicago'), (1909, 'Pittsburgh'), (1910, 'Philadelphia'), (1911, 'Philadelphia'), (1912, 'Boston'), (1913, 'Philadelphia'), (1914, 'Boston'), (1915, 'Boston'), (1916, 'Boston')]

从这里你可以制作一个字典,或字符串列表,或其他:

>>> dict(enumerate(winners, 1903))
{1903: 'Boston Americans', 1904: 'World Series Not Played in 1904', 1905: 'New York', 1906: 'Chicago', 1907: 'Chicago', 1908: 'Chicago', 1909: 'Pittsburgh', 1910: 'Philadelphia', 1911: 'Philadelphia', 1912: 'Boston', 1913: 'Philadelphia', 1914: 'Boston', 1915: 'Boston', 1916: 'Boston'}
>>> ['{}:{}'.format(winner, year) for year, winner in enumerate(winners, 1903)]
['Boston Americans:1903', 'World Series Not Played in 1904:1904', 'New York:1905', 'Chicago:1906', 'Chicago:1907', 'Chicago:1908', 'Pittsburgh:1909', 'Philadelphia:1910', 'Philadelphia:1911', 'Boston:1912', 'Philadelphia:1913', 'Boston:1914', 'Boston:1915', 'Boston:1916']

你可以很容易地剥离“在YYYY”部分,但最好的方法取决于短语的变化程度。

例如,如果您知道它是in YYYY,那么您可以使用类似

的内容
def strip_year(winner, year):
    in_year = ' in {}'.format(year)
    if winner.endswith(in_year):
        winner = winner[:-len(in_year)]
    return winner

然后使用字典理解(python> = 2.7):

>>> {year: strip_year(winner, year) for year, winner in enumerate(winners, 1903)}
{1903: 'Boston Americans', 1904: 'World Series Not Played', 1905: 'New York', 1906: 'Chicago', 1907: 'Chicago', 1908: 'Chicago', 1909: 'Pittsburgh', 1910: 'Philadelphia', 1911: 'Philadelphia', 1912: 'Boston', 1913: 'Philadelphia', 1914: 'Boston', 1915: 'Boston', 1916: 'Boston'}

答案 1 :(得分:1)

假设:

my_dict = {"States" : ["Boston Americans", "World Series Not Played in 1904", "New York",  
           "Chicago", "Chicago", "Chicago"
           "Pittsburgh", "Philadelphia", "Philadelphia",
           "Boston", "Philadelphia", "Boston", "Boston","Boston"]}

然后这样做:

years = 1906
for key in my_dict.keys():
  year_list = []
  for year in my_dict[key][0].split(","):
    if re.search(start,year):
      year_list.append(year)
    else:
      year_list.append(year + ":" + years)
    years += 1
  my_dict[key] = year_list

答案 2 :(得分:1)

类似的东西:

>>> a = ['a','b','c','d in 1906','e']
>>> b = range(1903,1903+len(a))
>>> b
[1903, 1904, 1905, 1906, 1907]
>>> zip(a,b)
[('a', 1903), ('b', 1904), ('c', 1905), ('d in 1906', 1906), ('e', 1907)]
>>> c = zip(a,b)
>>> d = [(i[0][:-7],i[1]) if i[0].endswith(str(i[1])) else (i[0],i[1]) for i in c]
>>> d
[('a', 1903), ('b', 1904), ('c', 1905), ('d ', 1906), ('e', 1907)]

然后您可以使用dict(d)来获取字典

答案 3 :(得分:1)

使用Python的列表推导并定义一个辅助函数,该函数将文本与年份连接起来(如果它们尚未存在)。

您可以使用enumerate的可选第二个参数来表示 start 值 - 您的第一年。

def add_year_to(state, year):
    year = str(year)
    return state if state.endswith(year) else ':'.join((state, year))


states_with_years = [add_year_to(state, year) 
                     for year, state
                     in enumerate(states, 1903)]