如何使用Python中的循环来反转列表的一部分? [英] How can I reverse a section of a list using a loop in Python?
本文介绍了如何使用Python中的循环来反转列表的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一些帮助,使用循环来反转Python中列表的一部分.
我有一个列表:mylist = ['a', 'b', 'c', 'd', 'e', 'f']
也有一个索引编号,该编号将告诉您从何处开始反转.例如,如果反向索引号为3,则它必须是这样的:['d', 'c', 'b', 'a', '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']
我目前拥有的是:
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) )
哪个返回['c', 'b', 'a', 'f', 'e', 'd']
如何更改我的代码,以使其打印出['d', 'c', 'b', 'a', 'e', 'f']
?
How can I alter my code, so that it prints out ['d', 'c', 'b', 'a', 'e', 'f']
?
推荐答案
是否可以复制列表?
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))
出局:
In function reverse()
['d', 'c', 'b', 'a', 'e', 'f']
这篇关于如何使用Python中的循环来反转列表的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文