对于Python和Numpy中的数组和列表,以下行是等效的:
itemlist = []
for j in range(len(myarray)):
item = myarray[j]
itemlist.append(item)
以及:
itemlist = []
for item in myarray:
itemlist.append(item)
我对项目列表的顺序感兴趣。在我尝试过的几个例子中,它们是相同的,但它是否可以保证?例如,我知道C中的foreach
语句不能保证顺序,我应该小心处理它。
Tags:
是的,完全有保证。
for item in myarray
(其中myarray
是一个序列,它包括numpy的数组、内置列表、Python的数组、数组等),实际上在Python中等同于:对于某些幻象变量
_aux
;-)。顺便说一下,您的两个构造也相当于名单上有保证。我认为与您的C#示例更相关的Python是遍历字典中的键,而字典中的键并不能保证以任何顺序排列。
for <element> in <iterable>
结构只担心iterable
提供返回某些内容的next()
函数。不能保证这些元素在for..in
语句的域上以任何顺序返回;列表是一种特殊情况。是的,Python Language Reference保证了这一点(重点是我的):
相关问题 更多 >
编程相关推荐