Skip to main content
 首页 » 编程设计

python之不了解切片在 python 中的作用

2025年05月04日29powertoolsteam

这是设置:

words = ['cat', 'window', 'defenestrate'] 
    for w in words: 
        print(w, len(w)) 

然后我输入:

>>> for w in words[:]:  # Loop over a slice copy of the entire list. 
...     if len(w) > 6: 
...         words.insert(0, w) 
... 

我不明白 insert(0, w) 中的 0 是什么 正在做。当我用另一个号码更改它时 输出保持不变。

最终输入/输出:

>>> words 
['defenestrate', 'cat', 'window', 'defenestrate'] 

请您参考如下方法:

insert 的第一个参数告诉 insert 在什么索引处放置新项目到列表中。由于您只有一个超过 6 个字符的单词,因此您发布的代码将 defenestrate 添加到现有列表的开头。

来自docs :

list.insert(i, x)

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).