gpt4 book ai didi

Python 插入与 Ruby 插入

转载 作者:数据小太阳 更新时间:2023-10-29 08:16:18 26 4
gpt4 key购买 nike

Python和Ruby都有insert方法。

python :

>>> a=[1,2,3,4,5]
>>> a.insert(0, 0)
>>> a
[0, 1, 2, 3, 4, 5]

ruby :

a=[1,2,3,4,5]
# => [1, 2, 3, 4, 5]
a.insert(0,0)
# => [0, 1, 2, 3, 4, 5]

它们的效果是一样的,但是如果给负数,结果就不同了。

python :

>>> a=[1,2,3,4,5]
>>> a.insert(-1, 6)
>>> a
[1, 2, 3, 4, 6, 5]

ruby :

a=[1,2,3,4,5]
# => [1, 2, 3, 4, 5]
a.insert(-1, 6)
# => [1, 2, 3, 4, 5, 6]

为什么会有这种差异?怎么理解?

最佳答案

在python中:insert(x, val),表示插入到x之前的位置。

so, a.insert(-1, 6)-> put the 6 before -1(location)

在ruby中:表示插入到这个位置x。

so, a.insert(-1, 6)-> put the 6 at -1.

关于Python 插入与 Ruby 插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33338984/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com