这个问题也许微不足道。如何将从1903年开始到2009年结束的一年添加到列表中的106项,而不创建一个长长的巨大的年份列表 但是用一年的时间来绕开它?在
例如:
States : Boston Americans, World Series Not Played in 1904, New York,
Chicago, Chicago, Chicago
Pittsburgh, Philadelphia, Philadelphia,
Boston, Philadelphia, Boston, Boston,Boston]`
为此:
^{pr2}$我知道你可以给单子上的每一项加上一个数字
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
但这对我来说是新的。我通常会有更多的展示,但我真的不知道 如何编写代码。在
假设:
这样就可以做到:
^{pr2}$如果你有一份获奖名单,比如:
您可以使用
^{pr2}$enumerate
将这些与数字关联起来:从这里你可以做一个dict,或者一个字符串列表,或者别的什么:
你可以很容易地去掉“inyyyy”部分,但最好的方法取决于短语的变化程度。在
例如,如果您知道它是
in YYYY
,那么您可以使用类似于然后使用字典理解(python>;=2.7):
像这样:
然后你可以用
dict(d)
来获取字典相关问题 更多 >
编程相关推荐