我想更快地列印一些變數。我正在使用的代碼是:
A_PR=3
B_PR=4
C_PR=6
print('the value of the model A is: ', A)
print('模型B的值是:', B)
print('the value of the model C is:', C)
我在考慮用for的回圈,但我不能使它發揮作用。
uj5u.com熱心網友回復:
你可以這樣使用字串格式化:
A_PR=3
B_PR=4
C_PR=6
print('Model A: {})
模型B:{}。
模型C:{}'.format(A_PR, B_PR, C_PR)
或者你可以將這些值嵌入到一個陣列中,并在該陣列上回圈。使用ASCI值,你可以列印A-Z模型的結果
。A_PR=3
B_PR=4
C_PR=6
model_results = [A_PR, B_PR, C_PR] 。
for idx, result in enumerate(model_results)。
print('Model {}: {}'.format(chr(idx 65), result)
輸出:
模型A:3。
模型B:4。
模型C:6。
uj5u.com熱心網友回復:
model_dict = {'A'/span>: 3, 'B':4, 'C':6,}。
for k,v in model_dict.items()。
print(f "the value of model {k} is: {v}")
這是我使用python f strings和dictionary制定的一個簡單解決方案。
uj5u.com熱心網友回復:
如果你真的想這樣做,你就必須通過存盤在另一個變數中的名字來訪問這些變數。有些人稱它為 "動態變數名"。如果你真的想這么做,有一個選擇是使用globals():
for x in ['A/span>, 'B', 'C'] 。
print(f'The value of the model {x} is: ', globals()[x '_PR'])
# 模型A的值是。3
# 模型B的值是:4。
# 模型C的價值是。6
但是這不是推薦的:見如何創建可變變數?.
。因此,更好的選擇之一可能是使用一個可迭代的資料型別,例如dict:
models = {'A'/span>: 3, 'B': 4, 'C'/span>: 6}。
for x in ['A'/span>, 'B'/span>, 'C'/span>] 。
print(f'The value of the model {x} is: {models[x]}')
可以使用items來進一步簡化,盡管我不是很喜歡這樣做,如果我想保留順序的話。
models = {'A'/span>: 3, 'B': 4, 'C'/span>: 6}。
for k, v in models.items():
print(f'The value of the model {k} is: {v}')
(一個dict確實保留了順序,但在我看來,我把dict視為在概念上沒有被排序)。
uj5u.com熱心網友回復:
像這樣的東西應該可以作為一個帶有for回圈的小字典。簡單地解壓鍵和值。
PR = {
"A_PR"/span>。3, "B_PR" :4 , "C_PR":6,
}
for k,v in PR.items():
print(f'the value of the model {k} is: {v}')
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/328910.html
標籤:
