简体   繁体   中英

Reversing a list within a list

I wrote the function below and it works if the len(list_of_list) is even. I'm having trouble when it's odd. When I run it, it ends up with an Assertion Error. How do I reverse only the elements in the first and last list index and not the ones in between when the list of lists is odd?

def flip_diag(list_of_list):

    for i in range(int(len(list_of_list) % 2 != 0)):
        list_of_list[0][::-1] = reversed(list_of_list[0][::-1])
        list_of_list[-1][::-1] = reversed(list_of_list[-1][::-1])

    for i in range(int(len(list_of_list) % 2 == 0)):
        reversed_list = [elem[::-1] for elem in list_of_list]
        return reversed_list


if __name__ == '__main__':
    
    assert flip_diag([[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]]) == [[0, 0, 0, 1],[0, 0, 2, 0], [0, 3, 0, 0], [4, 0, 0, 0]]
    assert flip_diag([[0, 0, 0], [0, 1, 0], [0, 0, 1]]) == [[0, 0, 0], [0, 1, 0], [1, 0, 0]]
    assert flip_diag([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) == [[0, 0, 1], [0, 1, 0], [1, 0, 0]]
    assert flip_diag([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[3, 2, 1], [4, 5, 6], [9, 8, 7]]

If the length of list_of_list is odd, you can have the below for loop in place to only reverse the first and last index elements each list inside list_of_list:

>> list_of_list = [[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0]]
>> for i in range(int(len(list_of_list) % 2 != 0)):
>>    reversed_list = [elem[-1:-2:-1]+elem[1:-1]+elem[0:1] for elem in list_of_list]
>>    print(reversed_list)

[[0, 0, 0, 1], [0, 2, 0, 0], [0, 0, 3, 0]]

If you want to use map and lambda you can do it like below:

>> list_of_list = [[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0]]
>> for i in range(int(len(list_of_list) % 2 != 0)):
>>     reversed_list = list(map(lambda elem: elem[-1:-2:-1]+elem[1:-1]+elem[0:1] ,list_of_list))
>>     print(reversed_list)
[[0, 0, 0, 1], [0, 2, 0, 0], [0, 0, 3, 0]]

one way to do it via list comprehension :

def flip_diag(list_of_list):
    if len(list_of_list) % 2 != 0:
        return [item[::-1] if index in [0, len(list_of_list)-1] else item for index, item in enumerate(list_of_list)]
    return [item[::-1] for index, item in enumerate(list_of_list)]

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