我正在嘗試獲得以下輸出
water:300ml
milk:200ml
coffee:100g
money:$0
問題是 ml、g 和 $ 不是我需要使用的字典的一部分,我無法將字典中的整數轉換為字串,因為它們確實需要在以后的計算中使用。
當然,美元符號很棘手,因為它必須在前面。
我試過這段代碼,但它不起作用,我就是想不出一個主意。TIA
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"money": 0,
}
for k,v in resources.items():
levels= ['ml', 'ml', 'g', '$']
print(k, ':', v)
for level in levels:
totals = (f'{v}{level}')
print(totals)
uj5u.com熱心網友回復:
如果你要重用這個操作,你可以定義一個string.Template
import string
template = string.Template("""water:${water}ml
milk:${milk}ml
coffee:${coffee}g
money:$$${money}""") # first 2 dollar signs are an escape to write the $
print(template.substitute(resources))
這使
water:300ml
milk:200ml
coffee:100g
money:$0
這可能會使您更容易考慮您希望輸出的外觀。
這里的語法是寫${var_name},然后在你的字典中有一個對應的鍵'var_name'。當你需要寫一個美元符號時,你必須用雙美元符號對其進行轉義$$。
uj5u.com熱心網友回復:
您可以將級別串列移到回圈之外,并使用簡單的計數器訪問其索引。
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"money": 0,
}
levels = ['ml', 'ml', 'g', '$']
count = 0
for k, v, in resources.items():
if k != 'money':
totals = (f'{k}:{v}{levels[count]}')
else:
totals = (f'{k}:{levels[count]}{v}')
print(totals)
count = 1
編輯:您還可以使用 zip 同時遍歷字典和串列。我認為這比上面的計數器更 Pythonic。
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"money": 0,
}
levels = ['ml', 'ml', 'g', '$']
for (k, v), level in zip(resources.items(), levels):
if k != 'money':
totals = (f'{k}:{v}{level}')
else:
totals = (f'{k}:{level}{v}')
print(totals)
uj5u.com熱心網友回復:
fstrings 的缺點之一是您不能使用延遲擴展。不過,您總是可以使用舊樣式。
format ={ 'water' : '%sml', 'milk' : '%sml', 'coffee':'%sg', 'money':'$%s' }
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"money": 0,
}
dict ( (k, format [k] % v ) for k,v in ressources.items() )
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/444689.html
上一篇:在字典中查找特定值的對應鍵
