python - [for 'elem' in myList] 与 [for 'i' in range(x, y)] 的区别是什么,引用列表元素

标签 python list for-loop

我使用 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/

相关文章:

python - 如何在 Foundry Nuke 中获取项目尺寸?

python - Numpy 图像数组根据二进制类别设置像素维度值

Python 本地日期时间月份

python - 如何在Python中按数据框过滤列表?

C# XML 序列化集合

python - 比较 2 个 Python 列表的顺序

java - 在 Java 中生成以不同数字开头的数字模式

javascript减少所有数组值的函数总和

java - 在同一行中循环不同的结束条件?

python - 花式索引 numpy 矩阵 : one element per row