简体   繁体   English

Python 枚举和 for 循环 output

[英]Python enumerate and for loops output

I have 2 questions regarding the following code:我对以下代码有 2 个问题:

  1. Why do I lose (0, 1) from enum_l1 and (0, 3) from enum_l2 after the for loops?为什么在 for 循环之后我会从 enum_l1 中丢失 (0, 1) 并从 enum_l2 中丢失 (0, 3)?
  2. If I do not put the first 2 prints as comments, I will not see the last 2 prints (in short, the program will only display "enum_l1 before:" and "enum_l2 before:" without "enum_l1 after:" and "enum_l2 after:").如果我不将前 2 个打印作为注释,我将看不到最后 2 个打印(简而言之,程序将只显示 "enum_l1 before:" 和 "enum_l2 before:" 而没有 "enum_l1 after:" 和 "enum_l2 after :")。 The opposite is also true.反之亦然。 Why?为什么? Why does I need to add to see all 4 prints in this code?为什么我需要添加才能查看此代码中的所有 4 个打印件?
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.

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