How do I reverse a part (slice) of a list in Python?

前端 未结 7 810
灰色年华
灰色年华 2020-11-27 19:32

Why doesn\'t this work?

# to reverse a part of the string in place 
a = [1,2,3,4,5]
a[2:4] = reversed(a[2:4])  # This works!
a[2:4] = [0,0]             # Thi         


        
相关标签:
7条回答
  • 2020-11-27 20:16

    Here's a weird example and weirder solution using slicing and a bit of list fundamentals.

    Problem: Reverse a list in parts of two.

    I/P : [1,2,3,4,5,6]

    O/P: [3,2,1,6,5,4]

    Soln:

    [item for i in range(0,len(l),len(l)/2) for item in l[i:i+len(l)/2][::-1]]
    

    Problem: Reverse the letters of someones name.

    E.g Harry Porter

    O/p: yrraH retroP

    Soln:

    ' '.join(map(lambda x:x[::-1], s.split()))
    
    0 讨论(0)
提交回复
热议问题