Reputation: 35
I am trying to group the self.L list into groups of five and then reverse both individual groups I want my output to look as follows
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]]
The code I have
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()
When I run the code my output is
None
Upvotes: 0
Views: 71
Reputation: 6589
To create nested lists with 5 elements in each one, you can use 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)]
Then to reverse the order of the values in the nested lists you can use .reverse()
for elem in new_list:
elem.reverse()
print (new_list)
Output:
[[8, 67, 5, 3, 1], [865, 67, 45, 100, 90]]
Upvotes: 1
Reputation: 2691
Assuming we receive the initial list in the variable 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)
Upvotes: 0