以正确的方式为python插入方法使用索引

2024-06-02 11:02:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我在理解python中插入方法的内部情况时遇到了一些问题。我一直在尝试手动将元素插入到一个空数组中,其中一些工作正常,但其他元素(索引2和索引3)被替换。所以在这张图中,我认为q应该在2的索引中,d应该在3的索引中,但情况正好相反。我知道当我在索引3上分配'd'时,blist数组中没有足够的元素可以插入第三个索引

blist = []
blist.insert(1, "h")
blist.insert(3, "d")
blist.insert(2, "q")
blist.insert(0, "g")
blist.insert(4, "k")
intended output: ['g', 'h', 'q', 'd', 'k']

output: ['g', 'h', 'd', 'q', 'k']

如果有人能帮助我理解我可能做错了什么,我将不胜感激


Tags: 元素output情况数组手动insertblistintended
3条回答

如果插入的索引大于列表的长度,则字符串将插入列表的末尾。 这意味着如果您运行:

blist = []
blist.insert(1, "h")
blist.insert(3, "d")

列表如下所示:

["h","d"]

如果现在运行:blist.insert(2, "q"),它将把q放在索引2(列表的末尾)

如果您特别想要一个数组。数组需要首先从其他库(即numpy)导入或声明

如果要插入项目的索引不存在,则将在其他位置插入该索引

我建议在此环境中运行代码,这样您就可以看到在每个步骤中发生的情况,以及插入项目的位置: http://pythontutor.com/visualize.html#mode=edit

可以找到不同列表方法的列表: https://www.w3schools.com/python/python_ref_list.asp

代码运行完全正常

下面是对每一步发生的情况的解释

At this point there is one element in the list.
    blist.insert(1, "h")
    ['h']
The index of h -> 0

    blist.insert(3, "d")
    ['h', 'd']
At this point d is inserted at index 3 but as there is only one element in the list its index in the list is d -> 1

    blist.insert(2, "q")
    ['h', 'd', 'q']
A similar thing happens for 2 as well, it is inserted at index 2 and its index in the list becomes q -> 2

Same thing is happening on further insertions
    blist.insert(0, "g")
    ['g', 'h', 'd', 'q']

    blist.insert(4, "k")
    ['g', 'h', 'd', 'q', 'k']

相关问题 更多 >