如果您有获奖者名单,例如:
>>> 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'}