简体   繁体   English

“for x in range(3):print x”是否保证按顺序打印“0,1,2”?

[英]Is “for x in range(3): print x” guaranteed to print “0, 1, 2” in that order?

Is a loop of the form 是形式的循环

for x in range(3):
    print x

guaranteed to output 保证输出

0
1
2

in that order? 以该顺序? In other words, if you loop over a list with a for item in mylist statement, is the loop guaranteed to start at mylist[0] and proceed sequentially ( mylist[1] , mylist[2] , ...)? 换句话说,如果你for item in mylist语句中循环一个带有for item in mylist的列表,那么循环是否保证从mylist[0]并按顺序进行( mylist[1]mylist[2] ,...)?

Yes, the builtin list and range will always iterate in the order you expect. 是的,内置listrange将始终按您期望的顺序迭代。 Classes define their own iteration sequence, so the iteration order will vary between different classes. 类定义自己的迭代序列,因此迭代顺序将在不同的类之间变化。 Due to their nature set and dict (amongst others) won't iterate in a predictable order. 由于它们的性质setdict (以及其他)不会以可预测的顺序迭代。

You can define any iteration sequence you want for a class. 您可以为类定义所需的任何迭代序列。 For example, you can make a list that will iterate in reverse. 例如,您可以创建一个反向迭代的list

class reversedlist(list):
    def __iter__(self):
        self.current = len(self)
        return self

    def next(self):
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self[self.current]

x = reversedlist([0, 1, 2, 3, 4, 5])
for i in x:
    print i,
# Outputs 5 4 3 2 1 0

Yes it does. 是的,它确实。 It is not the for loop that guarantees anything, but the range function though. 它不是for循环保证任何东西,而是范围函数。 range(3) gives you an iterator that returns 0, then 1 and then 2. Iterators can only be accessed one element at a time, so that is the only order the for loop can access the elements. range(3)为您提供一个返回0,然后是1然后返回2的迭代器。迭代器一次只能访问一个元素,因此这是for循环可以访问元素的唯一顺序。

Other iterators (ones not generated by the range function for example) could return elements in other orders. 其他迭代器(例如,不由range函数生成的迭代器)可以返回其他顺序中的元素。

is the loop guaranteed to start at mylist[0] and proceed sequentially (mylist[1], mylist[2], ...)? 是保证从mylist [0]开始并按顺序进行的循环(mylist [1],mylist [2],...)?

When you use a for loop, the list gets used as an iterator. 使用for循环时,列表​​将用作迭代器。 That is, the for loop actually does not index into it. 也就是说,for循环实际上没有索引到它。 It just keeps calling the next function until there are no more elements. 它只是不断调用next函数,直到没有更多的元素。 In this way the for loop itself has no say in what order elements gets processed. 通过这种方式,for循环本身没有说明元素的处理顺序。

Yes, it is. 是的。

A python for loop like this: 像这样循环的python:

for e in list:
    print e

can be traslated as: 可以被翻译为:

iterator = list.__iter__()
while True:
    try:
        e = iterator.next()
    except StopIteration:
        break
    print e

So, while the "next" method of the object iterator returns values in the "correct" order you will get the elements in the "correct" order. 因此,当对象迭代器的“下一个”方法以“正确”顺序返回值时,您将以“正确”顺序获取元素。 For python list this is guaranteed to happen. 对于python列表,这保证会发生。

For more information look here and here 有关更多信息,请查看此处此处

Yes. 是。 for loops in Python traverse a list or an iter in order. Python中的for循环按顺序遍历listiter range returns a list in Python 2.x and an iterator in Python 3.x, so your for x in range(3) loop will indeed always be ordered. range返回Python 2.x中的列表和Python 3.x中的迭代器,因此你的for x in range(3)循环确实总是被排序。

However , the same cannot be said for dict s or set s. 但是dict s或set s也不能这样说。 They will not be traversed in order - this is because the order of their keys is undefined. 它们不会按顺序遍历 - 这是因为它们的键的顺序是不确定的。

Yes, it starts with the first element of a list and goes to the last. 是的,它从列表的第一个元素开始,然后转到最后一个元素。

Not all data types in python do that, such as dicts, but lists certainly do. 并非python中的所有数据类型都可以,例如dicts,但列表肯定会这样做。 range(x) certainly will. range(x)肯定会。

Yes. 是。

But with a dictionary there´s no order guaranteed. 但是有了字典,没有保证订单。

Yes. 是。 Python docs about For Loop say: 关于For Loop的 Python文档说:

Basically, any object with an iterable method can be used in a for loop in Python ... Having an iterable method basically means that the data can be presented in list form, where there's multiple values in an orderly fashion 基本上,任何具有可迭代方法的对象都可以在Python中的for循环中使用...具有可迭代方法基本上意味着数据可以以列表形式呈现,其中有序的多个值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM