When reading the source code of a big man, I found for Another use of the statement ,for Statement after the entire statement , Doubts arise in the heart , So I ran the code again and found that there was no error , And then through consulting materials and writing their own code test , Due to the limited articles available , I know only a little now , If you find something wrong, please let me know .
for The statement is also known before it is put in the back , It's a list derivation , for example :
l = [ i for i in range(10)]
I always thought that this method could only be used to write list derivation , But he can still use it
s1 = ''.join(
random.choice(string.digits + string.ascii_letters)
for i in range(1000)
)
"""
amount to
s2 = ''
for i in range(1000):
s2.join(random.choice(string.digits + string.ascii_letters))
"""
li = [i for i in range(2000) if i % 2 == 0]
d1 = {li.pop() : i for i in range(1000)}
"""
amount to
li = [i for i in range(2000) if i % 2 == 0]
d2 = {}
for i in range(1000):
d2[li.pop()] = i
"""
The sentence is not difficult to understand , intuitive , But why is this usage generally used in list derivation , Used in dictionary derivation ( I don't know how to call , Let's call it that for a moment ) But few of them . Then I found that the list derivation is faster than the list processing with a normal loop , But it is very unstable in the dictionary , Most of the time, ordinary loops run faster than dictionary derivation , As for other usages, there may be few scenarios .
As for why the list derivation is fast, please Baidu for details .
The more you learn, the more you find yourself ignorant , Heart tired ....