亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從字符串創建字典的問題

從字符串創建字典的問題

千巷貓影 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 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號