Home > other >  Python discussion
Python discussion

Time:09-27

Known x=zip (" ABC ", "1234"), then perform the list for the second time in a row (x) what you're gonna get result, please analyze the reasons why

CodePudding user response:

The first execution list (x), if the print is
[(' a ', '1'), (' b ', '2'), (' c ', '3')]

The second execution list (x), if the print is
[]

The reason why, is about to speak of from the source code of the zip function:
 
Def zip (* iterables) :
# zip (' ABC ', '1234') -- & gt; Ax By
Sentinel=object ()
Iterators=[iter (it) for it in iterables]
While iterators:
Result=[]
For it in iterators:
Elem=next (it, sentinel)
If elem is sentinel:
Return
Result. Append (elem)
Yield a tuple (result)

Source code analysis see: https://docs.python.org/zh-cn/3/library/functions.html#zip

Because the zip function used in the yield statement,
So x=zip (' ABC ', '1234'), zip function is not executed immediately, but to make x into a generator objects,
As to the generator objects, can only through the next function value one by one,
However, as the subsequent statement is a list (x), which makes the generator x iterative completely, all data and return all,
So, make a second list (x), x is an iteration of the generator, which is only return null
So the list (empty), the results [],

The building Lord, you can use the following code validation understand:
 
X=zip (' ABC ', '1234')
Print (next (x))
Print (next (x))
Print (next (x))
Print (next (x) # 4 times next stop will happen because met a null value iteration abnormal


Add:
Why use four next statement, abnormal happens in 4 times? The zip and use the function, without exception occurs when the list?
That's because the zip function in the source code for exception handling (using object to null replace)!
So, in the validation code I gave you, if change the next statement in the fourth to the following:
Print (next (x, object ()))
Is not an exception occurs, because use null values replaced the object,
  • Related