我想列印 result1 的 variable_1 和 result2 的 variable_3。我想嘗試并繼續使用類似的語法,我可以在其中指定對 result1 和 variable_1 的呼叫。我想列印并回憶這兩種情況。
我收到以下錯誤:TypeError: tuple indices must be integers or slices, not str
我該如何解決?
def a():
result1 = {}
if 2 > 1:
print("yes 1")
result1['variable_1'] = 2 2
result1['variable_11'] = 'yes11'
else:
print("no 1")
result1['variable_2'] = 'no1'
result2 = {}
if 3 < 2:
print("yes 2")
result2['variable_3'] = 'yes2'
else:
print("no 2")
result2['variable_4'] = 'no2'
return result1, result2
result1 = a()
result2 = a()
print(result1['variable_1'])
print(result2['variable_3'])
uj5u.com熱心網友回復:
您給定的代碼a()回傳兩個值。
所以你的代碼的作用如下:
result1 = (result1, result2)
result2 = (result1, result2)
其中括號內的值是基于 內的變數的變數a()。
你可以做什么:
def a():
result1 = {}
if 2 > 1:
print("yes 1")
result1['variable_1'] = 2 2
result1['variable_11'] = 'yes11'
else:
print("no 1")
result1['variable_2'] = 'no1'
result2 = {}
if 3 < 2:
print("yes 2")
result2['variable_3'] = 'yes2'
else:
print("no 2")
result2['variable_4'] = 'no2'
return result1, result2
result1, result2 = a()
print(result1['variable_1'])
print(result2['variable_3'])
減少混淆的更好方法:
def a():
r1 = {"variable_1": None,
"variable_11": None,
"variable_2": None}
if 2 > 1:
print("yes 1")
r1['variable_1'] = 2 2
r1['variable_11'] = 'yes11'
else:
print("no 1")
r1['variable_2'] = 'no1'
r2 = {"variable_3": None,
"variable_4": None}
if 3 < 2:
print("yes 2")
r2['variable_3'] = 'yes2'
else:
print("no 2")
r2['variable_4'] = 'no2'
return r1, r2
result1, result2 = a()
print(result1['variable_1'])
print(result2['variable_3'])
問題還源于您沒有默認值variable_3since in result2, 3 < 2is False, sor2['variable_4']已定義但未定義r2['variable_3']。
我將默認值設定為None; 但是您可以將其設定為任何您想要的。
也就是說,雖然上面的代碼有效,但我不完全確定您要做什么。
uj5u.com熱心網友回復:
您將兩個不同的變數都分配給同一事物:一個元組。你真正想要的是元組解包。所以不要這樣做:
result1 = a()
result2 = a()
做:
result1, result2 = a()
您這樣做是因為a()回傳 2 個不同的值,并且您想為每個值分配一個 var。相當于做
result1 = a()[0]
result2 = a()[1]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/456238.html
標籤:Python python-3.x 字典 if 语句
下一篇:將串列串列的字典轉換為元組的字典
