[英]Python enumerate and for loops output
I have 2 questions regarding the following code:我对以下代码有 2 个问题:
list1 = [1,2,3]
list2 = [3,1,2]
enum_l1 = enumerate(list1)
#print("enum_l1 before: ", list(enum_l1))
enum_l2 = enumerate(list2)
#print("enum_l2 before: ", list(enum_l2))
for count1, value1 in enum_l1:
for count2, value2 in enum_l2:
print("enum_l1 after: ", list(enum_l1))
print("enum_l2 after: ", list(enum_l2))
Output: Output:
enum_l1 before: [(0, 1), (1, 2), (2, 3)]
enum_l2 before: [(0, 3), (1, 1), (2, 2)]
enum_l1 after: [(1, 2), (2, 3)]
enum_l2 after: [(1, 1), (2, 2)]
Thank you.谢谢你。
enum_l1
is an iterator. enum_l1
是一个迭代器。 Inside the loop you extract the first element which is (0,1)
and then instead of printing count1, value1
you print the state of the iterator enum_l1
which misses the first instance.在循环中,您提取第一个元素
(0,1)
,然后打印count1, value1
而不是打印缺少第一个实例的迭代器enum_l1
的 state。
The behavior you are seeing inside the loop is equivalent to:您在循环中看到的行为等同于:
enum_l1 = enumerate(list1)
print(next(enum_l1))
print(list(enum_l1))
The enumeration
creates an iterator object.该
enumeration
创建了一个迭代器 object。 When you initialize a list with it (done inside the print statement), it consumes the iterator.当您使用它初始化列表时(在 print 语句中完成),它会使用迭代器。 There are no more values to return from it after that.
在那之后没有更多的值可以从它返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.