拆分字典的這個鍵/值的最佳方法是什么:
test_status: "2200/2204(99%)"
這樣我就得到了兩個值為整數的鍵:
test_status_excpected: 2204
test_status_got: 2200
uj5u.com熱心網友回復:
使用/和(作為分隔符進行拆分。
第一個值是剩下的/
第二個值是什么是右邊/和左邊(
然后將結果轉換為 int
myDict["test_status_excpected"] = int(myDict["test_status"].split("/")[0])
myDict["test_status_got"] = int(myDict["test_status"].split("/")[1].split("(")[0])
uj5u.com熱心網友回復:
pair = {'test_status': '2200/2204(99%)'}
for key, value in pair.items():
value = value[:9] # this will keep first 9 char which drops (99%) part
years = value.split("/")
new_pair = {
"test_status_excpected": years[1],
"test_status_got": years[0]
}
print(new_pair)
# output: {'test_status_excpected': '2204', 'test_status_got': '2200'}
uj5u.com熱心網友回復:
您可以使用re模塊。例如:
import re
test_status = "2200/2204(99%)"
m = re.findall('\d ', test_status)
print(m[0], m[1])
輸出:
2200 2204
筆記:
此代碼隱式假設在字串中至少會找到兩個數字序列
uj5u.com熱心網友回復:
使用索引拆分字串。
test_status_expected = dic_name["test_status"][:4]
test_status_got = dic_name["test_status"][5:9]
如果您不確定索引,可以使用如下:
test_status_expected = dic_name["test_status"][:dic_name["test_status"].index("/")]
test_status_got = dic_name["test_status"][dic_name["test_status"].index("/") 1:dic_name["test_status"].index("(")]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/436156.html
標籤:Python python-2.7 字典 分裂 整数
上一篇:使用用戶輸入創建路徑
下一篇:根據值的位置從多列創建字典
