如果你有獲獎名單,如:
>>> 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
,然後使用字典解析(蟒蛇> = 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'}
oops讓我改變這一點。 –
唯一棘手的問題是刪除「YYYY」部分。它們是否都具有相同的格式,即以「YYYY」結尾,還是有些類似於「1994--由於Strike而取消」? – DSM
在這一點上,不像年份那麼重要。感謝您的輸入。 –