In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to write good Python code". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
The so-called pythonic, I think it includes two aspects: first, the style of the code is in line with the characteristics of Python, can reasonably use the "syntax sugar" of Python; second, the code is concise and beautiful, high stability, good readability, easy to maintain and modify. The so-called "Python Zen" is not limited to Python, many ideas are universal programming.
For example, to implement traversal access to elements in a list, I have seen people write this many times:
For i in range (len (lst)): print (LST [I])
Such a student is likely to have previous experience with CAccord Cure + or Java. It's okay to write this functionally, but it's not concise enough, not pythonic enough. A better way to do this:
For i in lst: print (I)
This kind of grammar, which does not affect function, but can simplify the program and improve readability, we call it "Syntactic sugar". There are many similar examples in Python, to name a few:
1. Exchange the values of two variables, commonly written as follows:
Temp = aa = bb = temp
Pythonic is written:
A, b = b, a
2. Similar unpacking (unpacking) usage can also implement multiple functions that return values. Common way of writing:
Def func (a, b): result = [b, a] return resultr = func (a, b) x = r [0] y = r [1]
Pythonic is written:
Def func (a, b): return b, ax, y = func (a, b)
3. Read and write documents, common writing method:
F = open ('filename.txt') text = f.read () print (text) f.close ()
Pythonic is written:
With open ('filename.txt') as f: for line in f: print (line)
The advantage of with is that even if something goes wrong, it will help you close the file.
4. Concatenate strings, commonly written:
Letters = ['for l in letters,' eBay, 'lump,' lump,'o'] s =''for l in letters: s + = lprint (s)
Pythonic is written:
Print ('.join (letters))
5. For the previous example of traversing the list, if you want to bring an index, you can write:
For I, elem in enumerate (lst): print (I, elem)
Traversing dictionary entries:
For key, value in dct.items (): print (key, value)
6. Take out the elements greater than 0 in the list and generate a new list. Common way of writing:
New_lst = [] for i in lst: if I > 0: new_lst.append (I)
Pythonic is written:
New_lst = [i for i in lst if i > 0]
This is called "List comprehension" (there are many Chinese translations), and it can be said that it is a very pythonic usage.
Further, if you have a large amount of data and you just traverse the new list and do not need a list object, you can use a generator:
New_lst = (i for i in lst if i > 0) for i in new_lst: print (I)
This will save resources and improve execution efficiency.
7. Determine whether a value is True, empty list, or None.
If x = = True: passif len (y) = = 0: passif z = = None: pass
Pythonic is written:
If x: passif not y: passif z is None: pass
8. Get the corresponding value in the dictionary according to the key name, which is commonly written:
Value = dct [key]
The problem is that if key doesn't exist, the code pops up with an error. So you have to add more judgment.
Pythonic is written:
Value = dct.get (key, 0)
Use the get method instead, and if it doesn't exist, you get None, or the specified default value (in this case, 0).
Due to the limitation of space, the above are just some representative examples. But there must be a limit to everything, and the excessive pursuit of pythonic writing may also lead to a decline in the readability of the code. For example, some people like to write a lot of functions in one sentence, but this is not pythonic. Therefore, we need to have some design principles, but we do not have to stick to the specific form, otherwise we will get into the corner.
So how can learners write more pythonic code? In the final analysis, it is still a process of accumulating experience. It is impossible for a rookie to become an old bird overnight after reading this book and last class, but as long as he persists long enough. I would like to give you some suggestions:
Watch more. Look at the official library, excellent projects, and learn other people's code. And read some quality tutorials and experience sharing.
Search more. When you achieve a small function, search the Internet to see how others write it, and compare it to whether it is better than your own. For example: how to remove duplicate elements from a list. You can do this yourself through loops, but just search it and you'll know the use of list (set (x)).
Write more. Don't worry about efficiency and style before you write a few lines of code. In the end, we have to write enough code before we can have the moment of "enlightenment".
This is the end of the content of "how to write good Python Code". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.