为了账号安全,请及时绑定邮箱和手机立即绑定

从字符串创建字典的问题

从字符串创建字典的问题

千巷猫影 2023-05-23 10:47:09
我有以下字符串。我正在将它转换为字典,但我检索的输出不是预期的输出。result = ' Thomas got 99 and James got 95, Gerrard got 84 and Tim got 21'mydict = dict((k.strip(), v.strip()) for k,v in           (item.split('and') for item in result.split(',')))print(mydict)output is: {'Thomas got 99': 'James got 95', 'Gerrard got 84': 'Tim got 21'}我希望预期的输出如下所示 output is:{'Thomas': '99', 'James': '95', 'Gerrard': '84', 'Tim': '21'}谢谢
查看完整描述

3 回答

?
繁花如伊

TA贡献2012条经验 获得超12个赞

使用 zip() 函数从两个列表创建字典


import re

result = ' Thomas got 99 and James got 95, Gerrard got 84 and Tim got 21'

key = re.findall('[A-Z]+[a-z]+',result)

value = re.findall(r'\d+',result)

print(dict(zip(key,value)))

#{'Thomas': '99', 'James': '95', 'Gerrard': '84', 'Tim': '21'}


查看完整回答
反对 回复 2023-05-23
?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

使用正则表达式。


前任:


import re


result = ' Thomas got 99 and James got 95, Gerrard got 84 and Tim got 21'

print(dict(re.findall(r"(\w+) got (\d+)", result)))

输出:


{'Thomas': '99', 'James': '95', 'Gerrard': '84', 'Tim': '21'}


查看完整回答
反对 回复 2023-05-23
?
红糖糍粑

TA贡献1815条经验 获得超6个赞

尝试改变而不是得到,并且没有那么多“和”只是使用逗号所以做


result = ' Thomas got 99, James got 95, Gerrard got 84, Tim got 21'

mydict = dict((k.strip(), v.strip()) for k,v in 

      (item.split('got') for item in result.split(',')))

print(mydict)

在我的 IDE 中运行这个,结果就是你要找的,希望这有帮助


查看完整回答
反对 回复 2023-05-23
  • 3 回答
  • 0 关注
  • 90 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信