我正在尝试将self.L列表分组为五个组,然后反转两个单独的组 我希望我的输出看起来如下
step1.(group the list into two section of five)
[[1,3,5,67,8],[90,100,45,67,865]]
step2.(reverse the numbers within the two groups)
[[8,67,5,3,1],[865,67,45,100,90]]
我的代码
class Flip():
def __init__(self,answer):
self.Answer = answer
self.matrix = None
self.L = [1,3,5,67,8,90,100,45,67,865,]
def flip(self):
if self.Answer == 'h':
def grouping(self):
for i in range(0, len(self.L), 5):
self.matrix.append(self.L[i:i+5])
print(self.matrix)
if __name__ =='__main__':
ans = input("Type h for horizontal flip")
work = Flip(ans)
work.flip()
当我运行代码时,我的输出是
None
答案 0 :(得分:1)
要创建每个包含5个元素的嵌套列表,可以使用list comprehension:
lst = [1,3,5,67,8,90,100,45,67,865]
new_list = [lst[i:i+5] for i in range(0, len(lst), 5)]
然后,要反转嵌套列表中值的顺序,您可以使用.reverse()
for elem in new_list:
elem.reverse()
print (new_list)
输出:
[[8, 67, 5, 3, 1], [865, 67, 45, 100, 90]]
答案 1 :(得分:0)
假设我们收到变量L
中的初始列表:
L = [1,3,5,67,8,90,100,45,67,865]
L1 = L[0:5]
L2 = L[5:10]
L=[L1,L2]
print (L)
L1.reverse()
L2.reverse()
L=[L1,L2]
print (L)