数组中的“for x”是否总是导致排序的x?[Python/NumPy]

2024-10-02 18:14:04 发布

您现在位置:Python中文网/ 问答频道 /正文

对于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: 项目innumpy列表forlen顺序range
3条回答

是的,完全有保证。for item in myarray(其中myarray是一个序列,它包括numpy的数组、内置列表、Python的数组、数组等),实际上在Python中等同于:

_aux = 0
while _aux < len(myarray):
  item = myarray[_aux]
  ...etc...

对于某些幻象变量_aux;-)。顺便说一下,您的两个构造也相当于

itemlist = list(myarray)

名单上有保证。我认为与您的C#示例更相关的Python是遍历字典中的键,而字典中的键并不能保证以任何顺序排列。

# Always prints 0-9 in order
a_list = [0,1,2,3,4,5,6,7,8,9]
for x in a_list:
    print x

# May or may not print 0-9 in order. Implementation dependent.
a_dict = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
for x in a_dict:
    print x

for <element> in <iterable>结构只担心iterable提供返回某些内容的next()函数。不能保证这些元素在for..in语句的域上以任何顺序返回;列表是一种特殊情况。

是的,Python Language Reference保证了这一点(重点是我的):

 for_stmt ::=  "for" target_list "in" expression_list ":" suite
               ["else" ":" suite]

"The suite is then executed once for each item provided by the iterator, in the order of ascending indices."

相关问题 更多 >