【发布时间】:2016-09-29 19:53:37
【问题描述】:
你知道为什么我在输出的第二行打印了一个“1”吗?
def word_map(string):
dict = {}
for word in string.split():
word = filter(str.isalnum, word).lower()
word = word.split()
if word in dict:
dict[word] +=1
else:
dict[word] = 1
return dict
dict = word_map("This is a string , this is another string too")
for k in dict:
print k, dict[k]
结果是:
a 1
1
string 2
this 2
is 2
too 1
another 1
Process finished with exit code 0
【问题讨论】:
-
强制警告 - 不要使用
dict作为变量名 -
为什么? PyCharm 没有显示任何警告
-
@MonaJalal 它覆盖了内置的
dict函数。 -
请注意,
filter()在 Python 3 中发生了更改,并且在其输入为字符串时不再返回字符串。''.join(filter(...))将在 Python 2 和 3 中安全地工作。
标签: python string dictionary