报错原因
wordstring = """it was the best of times it was the worst of times.it was the age of wisdom it was the age of foolishness"""
wordstring = wordstring.replace(".","")
# print(wordstring)
wordlist = wordstring.split()
# print(wordlist)
wordfreq = []
for w in wordlist:
wordfreq.append(wordlist.count(w))
# print(wordfreq)
d = dict(wordlist,wordfreq)
print(d)
请教报错原因?? 本帖最后由 isdkz 于 2023-1-30 17:55 编辑
dict的用法错了,dict 最多只能接收一个位置参数,而且这个位置参数需要能迭代出两个元素的序列
所以我用 zip 将你的两个列表打包成 zip 对象,这样应该能符合你的需求
wordstring = """it was the best of times it was the worst of times.
it was the age of wisdom it was the age of foolishness"""
wordstring = wordstring.replace(".","")
# print(wordstring)
wordlist = wordstring.split()
# print(wordlist)
wordfreq = []
for w in wordlist:
wordfreq.append(wordlist.count(w))
# print(wordfreq)
d = dict(zip(wordlist,wordfreq)) # 改了这一行
print(d) zip很难理解,还有一种方法
d = {}.fromkeys(wordlist)
for i, key in enumerate(list(d.keys())):
d = wordfreq 歌者文明清理员 发表于 2023-1-31 08:24
zip很难理解,还有一种方法
用 zip 是比较优雅的做法,而且你那个 enumerate 的参数有点多此一举,直接用 d 就可以了
d = {}.fromkeys(wordlist)
for i, key in enumerate(d): # 这一行直接用 d 就可以
d = wordfreq isdkz 发表于 2023-1-31 10:28
用 zip 是比较优雅的做法,而且你那个 enumerate 的参数有点多此一举,直接用 d 就可以了
呵呵,因为自己没试过,用的是保险的方法
页:
[1]