我想知道如何將串列中每個元組中的元素加在一起。這是我的代碼:
def add_together():
list = [(2,3), (4,5), (9,10)]
for tuple in list:
#missing code goes here I think.
print('{} {} = {}'.format(x,y,a))
add_together()
我想要的輸出將從
2 3 = 5
我怎么得到它?
uj5u.com熱心網友回復:
您可以使用元組解包語法來獲取元組中的每個專案:
def add_together(lst):
for (x, y) in lst:
print('{} {} = {}'.format(x,y,x y))
lst = [(2,3), (4,5), (9,10)]
add_together(lst)
uj5u.com熱心網友回復:
嘗試這個 :
def add_together():
input_list = [(2,3), (4,5), (9,10)]
for tup in input_list:
#missing code goes here I think.
print('{} {} = {}'.format(tup[0],tup[1],tup[0] tup[1]))
add_together()
輸出 :
2 3 = 5
4 5 = 9
9 10 = 19
uj5u.com熱心網友回復:
您也可以使用 * 來解包元組
def add_together():
list = [(2, 3), (4, 5), (9, 10)]
for tupl in list:
print('{} {} = {}'.format(*tupl, sum(tupl)))
add_together()
印刷:
2 3 = 5
4 5 = 9
9 10 = 19
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/505443.html
上一篇:反轉SML中的串列
下一篇:如何訪問串列中字典中的條件項
