我使用 python (3.6.2) 查看了选择排序算法。
我认识到所有解决方案/示例都会使用明确的数字来引用列表中的索引。
示例:
def selection_sort(content):
content_length = len(content)
for position in range(content_length):
for next_pos in range(position+1, content_length):
if content[next_pos] < content[position]:
content[next_pos], content[position] = content[position], content[next_pos]
当我这样尝试时:
def selection_sort(content):
for position in content:
for next_pos in (content):
if next_pos < position:
position, next_pos = next_position, position
以及 content[next_pos]
和 content[position]
的一些变体。
我的解决方案什么也不做。甚至没有错误...列表按照插入函数的顺序返回。
为什么? :-)elem
就像 for elem in my_list:
和 content[i]
之间有什么区别。
或者我在这一行中遗漏了一些东西?
位置,next_pos = next_position,位置
最佳答案
在第二个片段中,实际上您正在交换两个与数组内容具有相同值的变量的值,实际数组保持不变。
position, next_pos = next_position, position
这仅交换具有数组元素值的两个有值(value)的值。
但这会通过按索引访问数组元素来更改数组的内容。
content[next_pos], content[position] = content[position], content[next_pos]
快乐编码:)
关于python - [for 'elem' in myList] 与 [for 'i' in range(x, y)] 的区别是什么,引用列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57029480/