Int*_*ond 3 python sorting algorithm
这是一个非常简单的python机制问题.为什么我不能在范围original_list中代替i而不是在范围内的i(0,len(original_list)).人们通常使用的范围超过前者吗?谢谢!
# "If I give you an array with negative and positive numbers (i.e. {3,2,-3,6,4,-7}) and asked you to sort it so that the negative numbers appeared first but you didn't change the relative order of the remaining numbers, how would you do it? (i.e. the final result would be {-3,-7,3,2,6,4}).
original_list = [3, 2, -3, 6, 4, -7]
pos_list = []
neg_list = []
for i in range(0, len(original_list)):
if original_list[i] < 0:
neg_list.append(original_list[i])
else:
pos_list.append(original_list[i])
print neg_list + pos_list
Run Code Online (Sandbox Code Playgroud)
在您的情况下,由于您不需要使用列表中项目的索引,您可以使用for in以下方法迭代它:
>>> for item in original_list:
... if item < 0:
... ...
Run Code Online (Sandbox Code Playgroud)
如果要迭代列表中项目的索引,请使用for in range(..):
>>> for i in range(len(original_list)):
... if original_list[i] < 0:
... ...
Run Code Online (Sandbox Code Playgroud)
或者,enumerate()如果在循环体中同时需要item和index,则可能还需要使用:
>>> for i, item in enumerate(original_list):
... if item < 0:
... ...
Run Code Online (Sandbox Code Playgroud)
通过这种方式,你也消除了使用original_list[i].
这种结构range(len(my_sequence))通常不被认为是惯用的Python.它将您的代码集中在比我们通常尝试编写的更低级别的机制上,这使得它更难以阅读.正因为如此,range在这里使用大多被视为人们习惯于在C等低级语言编码的人.
例如,参见雷蒙德·海廷格(Raymond Hettinger)关于将代码转换为美丽的惯用语的谈话- 他建议的第一件事就是改变for i in range(len(sequence))到for item in sequence它出现的地方; 然后,他继续提及enumerate并zip涵盖您可能会试图恢复使用的情况range.他还提到惯用的方法更快.除了Python内置类型(不出所料)优化以快速运行惯用构造之外,不难看出为什么这对于某些其他数据结构可能是正确的 - 例如,链接列表可以比随机访问具有更快的顺序,这意味着依赖的循环my_linked_list[i]可能变成二次时间操作而不是线性操作.
如果您在codereview.SE上遵循[python]标记,您可以不时看到类似的建议.