You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:swapList函数中len函数的作用是什么?无len也可运行

Python中swapList函数里len()的具体作用是什么?

你给出的网站代码里,len()函数的核心作用就是获取列表的长度,进而计算出最后一个元素的正索引。

具体拆解:

  • size = len(newList):调用len()得到列表newList的元素总数(比如示例里的列表长度是5)。
  • newList[size - 1]:因为Python列表的正索引从0开始,长度为n的列表,最后一个元素的正索引是n-1,所以用size - 1就能精准定位到列表的最后一个元素。

和你写的负索引写法对比:

你用numbers[-1]直接访问最后一个元素,这是Python提供的便捷语法(负索引),-1在底层其实就等价于len(numbers) - 1。网站的写法是用更基础的正索引逻辑实现,本质和负索引效果完全一致,只是这种写法更直观地展示了「如何通过列表长度推导最后一个元素的位置」,适合刚接触列表索引的学习者理解正索引的规则。

下面是你提到的两段代码:

网站提供的swapList代码:

def swapList(newList):
    size = len(newList)
    
    temp = newList[0]
    newList[0] = newList[size - 1]
    newList[size - 1] = temp
    return newList

newList = [12, 35, 9, 56, 24]
print(swapList(newList))

你编写的负索引实现代码:

def swapping(numbers):
    temp = numbers[0]
    numbers[0] = numbers[-1]
    numbers[-1] = temp
    return numbers

numbers = [12, 15, 18, 21, 24]
print(swapping(numbers))

内容的提问来源于stack exchange,提问作者ghanee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 21:12:47