作业:如何将新列表拆分为与输入列表相同的长度?

时间:2016-05-16 01:28:39

标签: python

对于这项任务,我们被指示编写一个程序,该程序将采用两个列表列表并将相应的值一起添加。例如,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]。如何保留原始列表的结构?

1 个答案:

答案 0 :(得分:2)

要使代码正常工作,请创建中间列表并附加它们:

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]]