[英]Why does the length of an array have to have a negative next to it when doing the outer loop
def sort(nums):
for i in range(len(nums)-1,0,-1):
for j in range(i):
if nums[j]>nums[j+1]:
temp = nums[j]
nums[j] = nums[j+1]
nums[j+1] = temp
nums = [5,3,8,6,7,2] sort(nums) print(nums) nums = [5,3,8,6,7,2] sort(nums) 打印(nums)
I am a beginner in python and i am learning bubble sort my question is what is the effect of putting -1 next to len(nums).我是 python 的初学者,我正在学习冒泡排序,我的问题是将 -1 放在 len(nums) 旁边有什么影响。
The range
takes three arguments, where the first argument is the first number in the sequence.该
range
采用三个参数,其中第一个参数是序列中的第一个数字。
The first index you iterate over is the last element in the list, hence you use len(nums)-1
so you get the valid index of the last item in nums
list, as indexes are zero-based in Python.您迭代的第一个索引是列表中的最后一个元素,因此您使用
len(nums)-1
以便您获得nums
列表中最后一项的有效索引,因为索引在 Python 中是从零开始的。
eg例如
nums = [5,3,8,6,7,2]
length = len(nums) # 6
last_index = length - 1 # 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.