Skip to main content
 首页 » 编程设计

python之为列表或字典中的每个项目添加年份

2025年05月04日15pander-it

这个问题可能微不足道。如何在列表中添加从 1903 年开始到 2009 年结束的年份到 106 个项目,而无需创建很长的 HUGE 年份列表 但是用一年绕过那些?

例如:

  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' 对象不可迭代

但这对我来说是新的。我通常会有更多的东西要展示,但我真的没有任何想法 如何对此进行编码。

请您参考如下方法:

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

>>> 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'] 

您可以很容易地删除“in 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'}