[英]Homework: How to split a new list into same length as input list?
對於此作業,我們被要求編寫一個程序,該程序將使用兩個列表列表並將相應的值相加在一起。 例如, addTables([[1,8],[2,7],[3,6],[4,5]],[[9,16],[10,15],[11,14],[12,13]])
應該返回[[10, 24], [12, 22], [14, 20], [16, 18]]
addTables([[1,8],[2,7],[3,6],[4,5]],[[9,16],[10,15],[11,14],[12,13]])
[[10, 24], [12, 22], [14, 20], [16, 18]]
。
我的代碼是:
def addTables(list1, list2):
newlist = []
for i in range(0, len(list1)):
for j in range(0, len(list1[0])):
x = ([list1[i][j] + list2[i][j]])
newlist = newlist + x
return newlist
這給了我所有正確的值,但是將它們顯示為一個列表[10, 24, 12, 22, 14, 20, 16, 18]
。 如何保留原始清單的結構?
為了使您的代碼正常工作,請創建中間列表並追加它們:
def addTables(list1, list2):
newlist = []
for i in range(0, len(list1)):
sublist = []
for j in range(0, len(list1[0])):
x = list1[i][j] + list2[i][j]
sublist.append(x)
newlist.append(sublist)
return newlist
或者,您也可以使用zip()
:
>>> l1 = [[1,8],[2,7],[3,6],[4,5]]
>>> l2 = [[9,16],[10,15],[11,14],[12,13]]
>>> [[sum(subitem) for subitem in zip(*item)]
for item in zip(l1, l2)]
[[10, 24], [12, 22], [14, 20], [16, 18]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.