【问题标题】:Move function with Splice in Python在 Python 中使用 Splice 移动函数
【发布时间】:2018-10-30 13:11:58
【问题描述】:

我正在试图弄清楚如何从 Javascript 到 Python 执行以下函数:

function arraymove(arr, fromIndex, toIndex) {
    var element = arr[fromIndex];
    arr.splice(fromIndex, 1);
    arr.splice(toIndex, 0, element);
}

当然,在 Python 中,我们会使用元组,我不确定是否有像 Splice 这样的函数来实现相同的结果。

【问题讨论】:

    标签: javascript python list function


    【解决方案1】:

    您可以使用insert 方法并仅使用一行代码移动 desired 元素。

    您必须删除它,然后在new 位置插入它。使用pop 方法可以从指定位置移除一个元素。

    l.pop(fromIndex)
    

    然后只需使用insert 方法并将您要插入元素的位置作为参数传递。

    l = [1,2,3,4,5]
    def arraymove(arr, fromIndex, toIndex):
      l.insert(toIndex, l.pop(fromIndex))
    
    print(l)
    arraymove(l, 3, 1)
    print(l)
    

    输出

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

    【讨论】:

    • 这很好用,我不知道 insert() 函数。谢谢!
    猜你喜欢
    • 2014-06-17
    • 2020-08-23
    • 1970-01-01
    • 2014-11-10
    • 2022-01-26
    • 2011-09-14
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    相关资源
    最近更新 更多