0

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
3
  • 2
    Please edit your question and fix the indentation first. Commented Mar 7, 2016 at 3:14
  • Yes, please revise your code and ensure it is all structured appropriately. Also, setting self.matrix = None is going to give you problems based on how you are using it. You seem to want to use this as a list, so just initialize it as one: self.matrix = [] Commented Mar 7, 2016 at 3:16
  • You define the function grouping inside the flip method (a closure), but 1/ you don't call grouping(), nor do you return any result from grouping. So you just print the still empty matrix. Commented Mar 7, 2016 at 3:19

2 Answers 2

1

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

You can simply reverse in the list comprehension.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.