求問一道Python新手題目

items=list(reversed(range(12)))
items[::3]=range(12,0,-3)
print(items)
用IDE得出了結果,是[12, 10, 9, 9, 7, 6, 6, 4, 3, 3, 1, 0],但是看不懂為什麼呀 :joy: 求大神解答

PS.不知道這個帖子可以分類到哪裡,如果歸類錯了求指正

1 个赞

这个问题是不是考虑问 chatgpt 可解?

贴一下我整理的 chatgpt 关于客户端的笔记:

mac app

iOS app (ios16+)
TestFlight

为什么用app ?

开发者说,

受不了每次打开 ChatGPT 都要先“验证你是人类”然后等半天才能用,就做了一个原生桌面客户端,随时随地都能响应。注意使用这个 App 需要你有自己的 ChatGPT 账号, 生成个 API key 就能用了,你也可以将自己的 key 分享给家人使用。iOS、iPadOS 版本马上就好。

限制:

  1. 自己有openai.com 账号
  2. 申请免费api(就是去官网点一下)
  3. 免费api月度限制5000。即、日均不超过166条 (第三点我群里看来的,没验证)
  4. 开代理

在Python的解释器里,自己打印下就能看到每行结果了:

>>> print(*list(reversed(range(12))))
11 10 9 8 7 6 5 4 3 2 1 0
>>> print(*items[::3])
11 8 5 2
>>> print(*range(12,0,-3))
12 9 6 3

如果还不理解,需要再翻翻对应函数的文档。

PS:初学编程,推荐去小甲鱼的论坛,那边学Python的人多,对新手很友好。

2 个赞

但是還是看不懂[12, 10, 9, 9, 7, 6, 6, 4, 3, 3, 1, 0]是哪裡來的 :sob:
小甲魚是什麼呀,我下載了CSDN,但是問答不能問作業,不過很好用幫助我很多

1 个赞

列表里面原来的元素替换了啊

1 个赞

謝謝你,我太傻了 :rofl: 都沒有意識到需要替換

https://fishc.com.cn/forum-173-1.html

1 个赞

好的,謝謝你!!

ChatGPT 给出了正确的解释 & 错误的结果

Python Code: items = list(reversed(range(12))) items[::3] = range(12, 0, -3) tell me the resulting value of the ‘items’ list and explain

Answer from ChatGPT The resulting value of the 'items' list after executing the given code will be [9, 6, 3, 12, 10, 7, 4, 1, 11, 8, 5, 2].

Explanation:

Here's the step by step explanation of the given code:

* The 'reversed' function is applied to the range between 0 and 12 (exclusive), which returns the reversed order of integers from 11 to 0. So, the 'items' list will be [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0].

* The slicing operation [::3] selects every 3rd element in the 'items' list starting from the first element. Thus, it selects [11, 8, 5, 2] from the list.

* The right-hand side of the assignment, which is range(12, 0, -3), creates a new list of integers starting from 12 and decrementing by 3 until 0 (exclusive). So, it generates [12, 9, 6, 3] in reverse order.

* Finally, the selected list [11, 8, 5, 2] is replaced with the new list [12, 9, 6, 3] using the assignment statement. Thus, the resulting value of the 'items' list is [9, 6, 3, 12, 10, 7, 4, 1, 11, 8, 5, 2].