gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:49:44 25 4
gpt4 key购买 nike

这是设置:

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).

关于python - 不了解切片在 python 中的作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36630585/

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