Home > Software engineering >  python Invert the order of double list elements with recursive functions
python Invert the order of double list elements with recursive functions

Time:06-12

Invert the value configured as a double list I'm trying to reverse the double list elements

I want to flip it over with a recursive function

xss1 == [[a1,a2], [b1,b2,b3,b4], [c1,c2,c3]]


#result
xss2 == [[c3,c2,c1], [b4,b3,b2,b1], [a2,a1]]

I want to make a result like xss2

def xxR(xs):
    if xs != []:
       
        return [xs[-1]]   xxR(xs[:-1])
    else:
        return []

I tried flipping the whole thing, but could you tell me the element flipping?

CodePudding user response:

It's a one-liner with list comprehension:

l = [["a1","a2"], ["b1","b2","b3","b4"], ["c1","c2","c3"]]
rslt = [sub_l[::-1] for sub_l in l][::-1]

Output:

[['c3', 'c2', 'c1'], ['b4', 'b3', 'b2', 'b1'], ['a2', 'a1']]

CodePudding user response:

Your solution was close. What you are missing is to reverse the current element before appending it to the return value:

def invert(xs):
    if not xs:
        return []
    return [xs[-1][::-1]]   invert(xs[:-1])

Output will be:

[['c3', 'c2', 'c1'], ['b4', 'b3', 'b2', 'b1'], ['a2', 'a1']]
  • Related