程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Use of Pythons for statement later

編輯:Python

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 ....

 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved