【问题标题】:Get element range in list and swap获取列表中的元素范围并交换
【发布时间】:2021-12-31 08:26:09
【问题描述】:

我想在python中按范围交换元素列表

我的代码是

List = [1,2,3,4,5,6]

def swap(list_, a, b):
    list_[a], list_[b] = list_[b], list_[a]


swap(List, 0, 5,)
print(List)

我的输出是

[6, 2, 3, 4, 5, 1]

但我想要的是列表索引范围交换

# my expected output 
n = 2 (add var by input)

#and it swapped to this
[3, 4, 5, 6, 1, 2]

【问题讨论】:

    标签: python-3.x list


    【解决方案1】:

    你可以这样使用:

    def swap(List, n):
        return List[n:] + List[:n]
    
    List = [1,2,3,4,5,6]
    n = input()
    
    print(swap(List, n))
    

    使用切片 (:),您可以按索引将列表拆分为子列表。然后你可以在return语句中重新组合它们

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 2013-12-17
      • 2018-12-22
      相关资源
      最近更新 更多