gpt4 book ai didi

Python:生成数字 1-10 的列表,但 1 出现在列表的末尾?

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

我刚刚开始学习如何使用 Python 编程,并且一直在通过一些练习来帮助我提高。对于其中一个练习,我必须编写埃拉托色尼筛法,作为其中的一部分,我想生成一个从 1 到 n 的列表。

我的代码如下:

def primelist(n): #returns a list of all primes lower than or equal to n
grid=[]
k=1
while k in range (1, n+1):
grid.insert(-1, k)
k+=1
return grid

这是我所能得到的,因为当我测试到目前为止所写的内容时:

print(primelist(10))

我的代码输出列表 [2, 3, 4, 5, 6, 7, 8, 9, 10, 1],我不明白为什么要这样做。任何解释将不胜感激!

最佳答案

在 Python 中,list.insert(index, item)实际上在 index 之前插入 item

因此 list.insert(-1, k)在 -1 之前插入 k。因此你的结果。

要正确的做你想做的,下面两行是等价的

list.insert(len(list), k)
list.append(k)

这两种方法都按预期修改实际列表(而不是返回新列表)。

在这里查看更多信息:https://mail.python.org/pipermail/tutor/2010-January/073754.html

关于Python:生成数字 1-10 的列表,但 1 出现在列表的末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38938688/

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