python-切换位置:列表[i],list [list.index(minimum)] = list [list.index(munimim)],列表[i]
谁能解释我,为什么不可能在我的功能中交换列表位置以进行选择? 这是我一开始写的,但是该功能返回与输入相同的列表:
def selection_sort(list):
for i in range(0, len(list)):
minimum = list[i]
for j in range(i + 1, len(list)):
if list[j] < minimum:
minimum = list[j]
list[i], list[list.index(minimum)] = list[list.index(minimum)], list[i]
return list
然后我尝试使用一个变量索引= list.index.index(最小),然后突然起作用。
def selection_sort(list):
for i in range(0, len(list)):
minimum = list[i]
for j in range(i + 1, len(list)):
if list[j] < minimum:
minimum = list[j]
index = list.index(minimum)
list[i], list[index] = list[index], list[i]
return list
谁能解释我的区别,为什么不融合第一个解决方案? 谢谢你!
could anyone explain me, why is it not possible to swap list positions in my function for selection sort?
This is what i wrote at first, but the function returns the same list as the input:
def selection_sort(list):
for i in range(0, len(list)):
minimum = list[i]
for j in range(i + 1, len(list)):
if list[j] < minimum:
minimum = list[j]
list[i], list[list.index(minimum)] = list[list.index(minimum)], list[i]
return list
Then I tried to use a variable index = list.index(minimum) and suddenly it worked.
def selection_sort(list):
for i in range(0, len(list)):
minimum = list[i]
for j in range(i + 1, len(list)):
if list[j] < minimum:
minimum = list[j]
index = list.index(minimum)
list[i], list[index] = list[index], list[i]
return list
Could anyone explain me the difference and why is it not corect the first solution?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
分配的右侧(
list [list.index(mix umimum)],list [i]
)首先计算,然后分配给左list [i], list [list.index(mixumim)]
。我猜下一部分,但是我假设
list [i]
分配给,然后list [list.index(munimum)]
。但是,由于您已经分配给list [i]
您已经修改了列表,然后再查找list.index(mixumime)
第二次。由于您没有在相同的列表中搜索,因此索引可能有所不同。您的第二次尝试一次计算索引,并在两个地方使用相同的值。
附带说明,最好不要将变量命名与Python内置名称相同。您的函数采用一个称为
list
的参数,以便“阴影”“内置”list
函数。您将无法在功能内部调用该函数,因为该名称已被盗。最好将其称为my_list
,array
或list_to_sort
等。The right hand side of the assignment (
list[list.index(minimum)], list[i]
) is computed first, then assigned to the tuple on the leftlist[i], list[list.index(minimum)]
.I'm guessing the next part, but I assume
list[i]
is assigned to, thenlist[list.index(minimum)]
. However, since you've already assigned tolist[i]
you've already modified the list before findinglist.index(minimum)
a second time. Since you're not searching in identical lists, the indexes may be different.Your second attempt calculates the index once and uses the same value in both places.
As a side note, it is good practice to not name variables the same as a python builtin name. Your function takes a parameter called
list
so that "shadows" the builtinlist
function. You wouldn't be able to call that builtin inside your function because the name has been stolen. Better to call itmy_list
,array
, orlist_to_sort
etc.