[英]Reversing a list within a list
我在下面写了 function,如果len(list_of_list)
是偶数,它就可以工作。 当它很奇怪时,我会遇到麻烦。 当我运行它时,它以一个断言错误结束。 当列表列表为奇数时,如何仅反转第一个和最后一个列表索引中的元素,而不是中间的元素?
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]]
如果 list_of_list 的长度是奇数,您可以使用下面的 for 循环来仅反转 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]]
如果你想使用map
和lambda
你可以这样做:
>> 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]]
通过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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.