简体   繁体   中英

Can anyone explain what am i doing wrong

Question:-Write a Python function transpose(m) that takes as input a two dimensional matrix m and returns the transpose of m. The argument m should remain undisturbed by the function.

def transpose(l):
m=l[:]
lst=[[] for x in range(len(m[0)]
for i in range(0,len(m)):
    for j in range(0,len(m[i])):
        lst[j].append(m[i][j])
return lst
l=[[1,2,3,4,5],[4,5,6,7,8,9]]

ERROR
lst[j].append(m[i][j])
IndexError: list index out of range

Your List l has two lists with 5 and 6 elements.

So, the range of j in range(len(m[1])) is 0 - 5 (6 numbers), which results in index out of range for lst (which only have 5 elements).

def transpose(l):
    lst=[[] for x in range(len(l[0]))]
    for i in range(len(l)):
        for j in range(len(l[i])):
            lst[j].append(l[i][j])
    return lst
l = [[1,2,3,4,5],[4,5,6,7,8]]

But I would add a checking part at the beginning of the function

def transpose(l):
    iterator = iter(l)
    lists_len = len(next(iterator))
    if not all(len(a) == lists_len for a in iterator):
        # Do something here

    lst=[[] for x in range(len(l[0]))]
    for i in range(len(l)):
        for j in range(len(l[i])):
            lst[j].append(l[i][j])
    return lst

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM