How can I reverse a section of a list using a loop in Python?

蹲街弑〆低调 提交于 2019-12-02 06:16:13

问题


I'm in need of a little help reversing a section of a list in Python using a loop.

I have a list: mylist = ['a', 'b', 'c', 'd', 'e', 'f']

Also have an index number, this number will tell where to start the reversing. For example, if the reverse-index number is 3, it needs to be something like this: ['d', 'c', 'b', 'a', 'e', 'f']

What I currently have:

def list_section_reverse(list1, reverse_index):
    print("In function reverse()")

    n_list = []

    for item in range( len(list1) ):
        n_list.append( (list1[(reverse_index - 1) - item]) )
        item += 1
    return n_list

mylist = ['a', 'b', 'c', 'd', 'e', 'f']
print( list_section_reverse(mylist, 3) )

Which returns ['c', 'b', 'a', 'f', 'e', 'd']

How can I alter my code, so that it prints out ['d', 'c', 'b', 'a', 'e', 'f']?


回答1:


Is it allowed to make a copy of the list?

def list_section_reverse(list1, reverse_index):
    print("In function reverse()")

    n_list = [ element for element in list1 ]

    for item in range( reverse_index + 1 ):
        n_list[ item ] = list1[ reverse_index - item ]
        item += 1

    return n_list

mylist = ['a', 'b', 'c', 'd', 'e', 'f']
print(list_section_reverse(mylist, 3))

Outs:

In function reverse()
['d', 'c', 'b', 'a', 'e', 'f']



回答2:


You can simply use:

def list_section_reverse(list1, reverse_index):
    return list(reversed(list1[:reverse_index+1])) + list1[reverse_index+1:]

Edit: The problem with your existing solution is that you keep reversing after reverse_index. If you have to use a loop, try this:

def list_section_reverse(list1, reverse_index):
    print("In function reverse()")

    n_list = list1[:]

    for i in range(reverse_index + 1):
        n_list[i] = list1[-i-reverse_index]
    return n_list

mylist = ['a', 'b', 'c', 'd', 'e', 'f']
print(list_section_reverse(mylist, 3))



回答3:


The pythonic solution:

list1[reverse_index::-1] + list1[reverse_index+1:]

Now, that's not using loops like you asked. Well, not explicitly... Instead we can break down the above into its constituent for loops.

def list_section_reverse(list1, reverse_index):
    if reverse_index < 0 or reversed_index >= len(list1):
        raise ValueError("reverse index out of range")
    reversed_part = []
    for i in range(reverse_index, -1, -1): # like for i in [n, n-1, ..., 1, 0]
        reversed_part.append(list1[i]

    normal_part = []
    for i in range(reverse_index + 1, len(list1)):
        normal_part.append(list1[i])

    return reversed_part + normal_part



回答4:


You can modify the list inplace using a slice.

mylist[:4] = mylist[:4][::-1]



回答5:


You can try this. This makes use of no slicing, and can use either a while loop or for loop.

    def reversed_list(my_list, index):
        result = []
        list_copy = my_list.copy()

        i = 0
        while i < index+1:
            result.append(my_list[i])
            list_copy.remove(my_list[i])
            i+=1

        result.reverse()

        return result + list_copy

Or with a for loop

    def reversed_list(my_list, index):
        result = []
        list_copy = my_list.copy()

        for i in range(len(my_list)):
            if i < index + 1:
                result.append(my_list[i])
                list_copy.remove(my_list[i])

        result.reverse()

        return result + list_copy


来源:https://stackoverflow.com/questions/37461321/how-can-i-reverse-a-section-of-a-list-using-a-loop-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!