In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "sharing 9 practical Python skills". In the operation of practical 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!
Clean up string input
The problem of cleaning up user input applies to almost all programs you write. In general, converting characters to lowercase or uppercase is sufficient, and sometimes you can use Regex to do this, but for complex situations, there may be a better way:
In this example, you can see that the white space characters "\ n" and "\ t" have been replaced by a single space, while "\ r" has been completely deleted. This is a simple example, but we can go a step further and use the unicodedata package and its combining () function to generate and map to generate a larger remap table that we can use to remove all accents from the string.
Slice the iterator
If you try to slice an iterator, you get a TypeError, which means that the generator object is not accessible by subscript, but there is a simple solution to this problem:
With itertools.islice we can create an islice object, which is an iterator that generates the desired items. It is important to note that this consumes all generator entries prior to the start of slice, as well as all items in the islice object.
Skip the beginning of an iterable object
Sometimes you have to deal with files that start with a variable number of lines (such as comments) that you don't want. Once again, itertools provides a simple solution to this problem:
This code snippet generates only the lines after the initial comment section. This is useful if we only want to discard some items (some lines in this case) at the beginning of the iterable object, and we don't know how many items there are.
A function with only keyword arguments (kwargs)
When using functions such as the following, it is helpful to create functions that only accept keyword arguments to provide (force) more clarity:
As you can see, this can be easily solved by placing a single * parameter before the keyword parameter. If we put the position parameter before the * parameter, it is obvious that the position parameter will also exist.
Create objects that support with statements
For example, we all know how to use the with statement to open a file or acquire a lock, but can we implement our own with statement? Of course, we can use the _ _ enter__ and _ _ exit__ methods to implement the context management protocol:
This is the most common way to implement context management in Python, but there is a simpler way to implement it:
The above code snippet implements the content management protocol using the contextmanager manager decorator. When entering the with block, the first part of the tag function (before yield) is executed, then the with block is executed, and finally, the rest of the tag function is executed.
Use _ _ slots__ to save memory
If you have ever written a program that creates a large number of instances of a class, you may notice that your program suddenly needs a lot of memory. This is because Python uses dictionaries to represent the properties of class instances, which makes it fast, but not memory efficient, which is usually not a problem. However, if it becomes a problem for your program, you can try using _ _ slots__:
In this case, when we define the _ _ slots__ attribute, Python uses a small fixed-size array instead of a dictionary to define the property, which greatly reduces the memory required for each instance. There are some drawbacks to using _ _ slots__-we cannot declare any new properties, and we can only use them on _ _ slots__. Also, classes with _ _ slots__ cannot use multiple inheritance.
Limit CPU and memory usage
If you don't want to optimize your program memory or CPU usage, you just want to limit it to a fixed size of memory, then Python has a library to do this:
Here we can see two options for setting the maximum CPU run time and the maximum memory usage limit. For CPU limits, we first get the soft and hard limits for a specific resource (RLIMIT_CPU), and then set it using the number of seconds specified by the parameter and the hard limit retrieved earlier. Finally, we register the signal, which will cause the system to exit if the CPU time exceeds the limit. For memory, we retrieve the soft and hard limits again and set it using setrlimit with size parameters and hard limits for retrieval.
Control what can be imported and what cannot be imported
Some languages have very obvious control mechanisms for exporting members (variables, methods, interfaces), such as Golang, where only members that begin with uppercase letters are exported. On the other hand, in Python, everything can be exported unless we use _ _ all__:
Based on the code snippet above, we know that only the bar function will be exported. Similarly, we can leave _ _ all__ empty so that when we import from this module, nothing will be exported and will result in AttributeError.
A simple way to implement comparison operators
Considering that there are already quite a few comparison operators-- _ _ lt__, _ _ le__, _ _ gt__, or _ _ ge___,-- it's quite annoying to implement all the comparison operators for a class. But what if there was an easier way to do it? functools.total_ordering would come in handy:
So, how does this work? the total_ordering decorator is used to simplify the process of implementing class instance sorting. We just need to define _ _ lt__ and _ _ eq__, which are the minimum values required for the mapping of the remaining operations, and the decorator will fill in the blanks for us.
That's all for sharing 9 practical Python tips. 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.