鱼C论坛

 找回密码
 立即注册
查看: 2863|回复: 4

[已解决]报错原因

[复制链接]
发表于 2023-1-30 17:45:02 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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)
请教报错原因??
最佳答案
2023-1-30 17:53:31
本帖最后由 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)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-1-30 17:53:31 | 显示全部楼层    本楼为最佳答案   
本帖最后由 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)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-1-31 08:24:45 | 显示全部楼层
zip很难理解,还有一种方法
d = {}.fromkeys(wordlist)
for i, key in enumerate(list(d.keys())):
    d[key] = wordfreq[i]
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-1-31 10:28:51 | 显示全部楼层
歌者文明清理员 发表于 2023-1-31 08:24
zip很难理解,还有一种方法


用 zip 是比较优雅的做法,而且你那个 enumerate 的参数有点多此一举,直接用 d 就可以了
d = {}.fromkeys(wordlist)
for i, key in enumerate(d):       # 这一行直接用 d 就可以
    d[key] = wordfreq[i]
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-1-31 10:47:05 | 显示全部楼层
isdkz 发表于 2023-1-31 10:28
用 zip 是比较优雅的做法,而且你那个 enumerate 的参数有点多此一举,直接用 d 就可以了

呵呵,因为自己没试过,用的是保险的方法
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-24 19:17

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表