如何反转列表中的子列表? [英] How do I reverse a sublist in a list in place?

查看:120
本文介绍了如何反转列表中的子列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该创建一个函数,该函数的输入是一个列表和两个数字,函数颠倒了它的位置由这两个数字表示的子列表。
例如这就是它应该做的:

 >>> lst = [1,2,3,4,5] 
>>> reverse_sublist(lst,0,4)
>>> lst [4,3,2,1,5]

我创建了一个函数,我不确定它是否到位。
这是我的代码:

$ $ p $ def reverse_sublist(lst,start,end):
sublist = lst [start:end]
sublist.reverse()
lst [start:end] =子列表
print(lst)


解决方案

  def reverse_sublist(lst,start,end):
lst [start: end] = lst [start:end] [:: - 1]
return lst


I'm supposed to create a function, which input is a list and two numbers, the function reverses the sublist which its place is indicated by the two numbers. for example this is what it's supposed to do:

>>> lst = [1, 2, 3, 4, 5] 
>>> reverse_sublist (lst,0,4) 
>>> lst  [4, 3, 2, 1, 5]

I created a function and it works, but I'm not sure is it's in place. This is my code:

def reverse_sublist(lst,start,end):
    sublist=lst[start:end]
    sublist.reverse()
    lst[start:end]=sublist
    print(lst)

解决方案

def reverse_sublist(lst,start,end):
    lst[start:end] = lst[start:end][::-1]
    return lst

这篇关于如何反转列表中的子列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆