In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what are the practical cases of Python", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what are the practical cases of Python"?
1. Collate string input
The problem of sorting out user input is extremely common in the programming process. In general, converting characters to lowercase or uppercase is sufficient, and sometimes you can use the regular expression module "Regex" to do this. But if the problem is complex, there may be a better way to solve it:
User_input = "This\ nstring has\ tsome whitespaces...\ r\ n" character_map = {ord ('\ n'):', ord ('\ t'):', ord ('\ r'): None} user_input.translate (character_map) # This string has some whitespaces...
In this example, you can see that the spaces "n" and "t" have been replaced with a single space, and "r" has been deleted. This is a very simple example. We can go one step further and use the "unicodedata" package to generate a large remap table and use the "combining ()" in it to generate and map. We can
two。 Iterator slice (Slice)
If you slice the iterator, a "TypeError" is returned, indicating that the generator object does not have a subscript, but we can solve this problem with a simple solution:
Import itertools s = itertools.islice (range (50), 10,20) for val in s:.
We can use "itertools.islice" to create a "islice" object, which is an iterator that produces the items we want. Note, however, that this operation uses all generator entries before slicing, as well as all items in the "islice" object.
3. Skip the beginning of an iterable object
Sometimes you have to deal with files that start with unwanted lines (such as comments). "itertools" once again provides a simple solution:
String_from_file = "" / / Author:. / / License:. / Date:. Actual content... "" Import itertools for line in itertools.dropwhile (lambda line: line.startswith ("/ /"), string_from_file.split ("): print (line)
This code only prints the content after the initial comment section. This approach is useful if we only want to discard the first part of the iterable object (the comment line that begins in this example) without knowing how long we want it to be.
4. A function that contains only keyword arguments (kwargs)
When we use the following function, it is helpful to create a function that requires only keyword arguments as input to provide a clearer function definition:
Def test (*, a, b): pass test ("value for a", "value for b") # TypeError: test () takes 0 positional arguments... Test (a = "value", b = "value 2") # Works...
As you can see, adding a "*" before the keyword parameter can solve this problem. If we put some parameters before the "*" parameter, they are obviously positional parameters.
5. 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 context expressions? Yes, we can use "_ _ enter__" and "_ _ exit__" to implement the context management protocol:
Class Connection: def _ init__ (self):... Def _ _ enter__ (self): # Initialize connection... Def _ _ exit__ (self, type, value, traceback): # Close connection... With Connection () as c: # _ _ enter__ () executes... # conn.__exit__ () executes
This is the most common way to implement context management in Python, but there is a simpler way:
From contextlib import contextmanager @ contextmanager def tag (name): print (f "") yield print (f "") with tag ("H2"): print ("This is Title.")
The above code implements the content management protocol using contextmanager's manager decorator. The first part of the tag function (the part before yield) is executed when you enter the with block, then the with block is executed, and finally the rest of the tag function is executed.
6. Save memory with "slots"
If you have ever written a program that creates a large number of instances of some kind, you may have noticed that your program suddenly needs a lot of memory. That's because Python uses dictionaries to represent the properties of class instances, which makes it fast, but not very efficient in memory use. Usually, this is not a serious problem. However, if your program is seriously affected by this, try "_ _ slots__":
Class Person: _ _ slots__ = ["first_name", "last_name", "phone"] def _ _ init__ (self, first_name, last_name, phone): self.first_name = first_name self.last_name = last_name self.phone = phone
When we define the "_ _ slots__" attribute, Python does not use a dictionary to represent the attribute, but uses a small fixed-size array, which greatly reduces the memory required for each instance. Using "_ _ slots__" also has some disadvantages: we cannot declare any new properties, we can only use existing properties on "_ _ slots__". Also, classes with "_ _ slots__" cannot use multiple inheritance.
7. Limit "CPU" and memory usage
If you do not want to optimize the program's memory or CPU usage, but want to directly limit it to a certain number, Python also has a corresponding library that can do this:
Import signal import resource import os # To Limit CPU time def time_exceeded (signo, frame): print ("CPU exceeded...") Raise SystemExit (1) def set_max_runtime (seconds): # Install the signal handler and set a resource limit soft, hard = resource.getrlimit (resource.RLIMIT_CPU) resource.setrlimit (resource.RLIMIT_CPU, (seconds, hard)) signal.signal (signal.SIGXCPU, time_exceeded) # To limit memory usage def set_max_memory (size): soft, hard = resource.getrlimit (resource.RLIMIT_AS) resource.setrlimit (resource.RLIMIT_AS (size, hard))
We can see that in the code snippet above, there are options to set both the maximum CPU run time and the maximum memory usage limit. When limiting the running time of CPU, we first get the soft limit and hard limit for that particular resource (RLIMIT_CPU), and then set it using the number of seconds specified by the parameter and the hard limit previously retrieved. Finally, if the running time of the CPU exceeds the limit, we will signal that the system exits. In terms of memory usage, we retrieve the soft and hard limits again and set it with "setrlimit" with the "size" parameter and the hard limits we retrieved earlier.
8. Controls what can / cannot be imported
Some languages have a very obvious mechanism for exporting members (variables, methods, interfaces). For example, in Golang, only members that begin with uppercase letters are exported. However, in Python, all members are exported (unless we use "_ _ all__"):
Def foo (): pass def bar (): pass _ _ all__ = ["bar"]
In the above code, we know that only the "bar" function has been exported. Similarly, we can leave "_ _ all__" empty so that nothing is exported, resulting in a "AttributeError" when imported from this module.
9. A simple way to implement comparison operators
It is tedious to implement all the comparison operators (such as _ _ lt__, _ _ le__, _ _ gt__, _ _ ge__) for a class. Is there an easier way to do this? At times like this, "functools.total_ordering" is a good helper:
From functools import total_ordering @ total_ordering class Number: def _ _ init__ (self, value): self.value = value def _ lt__ (self, other): return self.value
< other.value def __eq__(self, other): return self.value == other.value print(Number(20) >Number (3)) print (Number (1)
< Number(5)) print(Number(15) >= Number (15)) print (Number (10)
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.