In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "what are the skills of learning Python". The explanation in this article is simple and clear, easy to learn and understand. Please follow the ideas of Xiaobian and go deep into it slowly to study and learn "what are the skills of learning Python" together!
Sort string input
The problem of organizing user input is extremely common in programming. Usually, converting characters to lowercase or uppercase is enough, 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 string has some whitespaces... " character_map = { ord( ) : , ord( ) : , ord( ) : 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 single spaces, and the "r" has been deleted. This is just a very simple example, we can go further, using the "unicodedata" package to generate a large remapping table, and using the "combining()" to generate and map, we can
Iterator Slice
If we slice the iterator, we will return a TypeError, indicating that the generator object has no subscript, but we can solve this problem with a simple solution:
Python tutorial/tool/method/puzzle +V: itz992itertools.islice object at 0x7 f70fab88138> for val in s: ...
We can use itertools.islice to create an islice object, which is an iterator that produces the items we want. Note, however, that this operation uses all generator items prior to slicing, as well as all items in the "islice" object.
Skip the beginning of iterable objects
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 prints only what follows the initial comment section. This is useful if we want to discard only the first part of the iterable object (in this case, the first comment line), but we don't know how long we want that part to be.
Functions with keyword arguments only (kwargs)
When we use the following functions, it helps to create functions that require only keyword arguments as input to provide clearer function definitions:
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 solves this problem. If we put some parameters before the "" parameter, they are obviously positional parameters.
Creating objects that support the "with" statement
For example, we all know how to open a file or acquire a lock using a "with" statement, but can we implement our own contextual expressions? Yes, we can use "enter" and "exit" to implement context management protocols:
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 are simpler ways:
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 the manager decorator of contextmanager. The first part of the tag function (before yield) is executed when entering the with block, then the with block is executed, and finally the rest of the tag function is executed.
Save memory with slots
If you've ever written a program that creates a large number of instances of a class, you've probably noticed that your program suddenly needs a lot of memory. That's because Python uses dictionaries to represent attributes of class instances, which makes it fast but less memory efficient. Usually, this is not a serious problem. However, if your program is severely 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 doesn't use dictionaries to represent attributes, but small fixed-size arrays, which greatly reduces the memory required for each instance. There are also some disadvantages to using slots: we cannot declare any new attributes, we can only use existing attributes on slots. Also, classes with "slots" cannot use multiple inheritance.
Limit CPU and memory usage
If you don't want to optimize your program's memory or CPU usage, but want to limit it directly to a certain number, Python has a library that does the same:
Python tutorial/tool/method/puzzle +V: itz992import 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))
As you can see, in the code snippet above, there are options for setting both maximum CPU runtime and maximum memory usage limits. When limiting CPU runtime, we first obtain the soft and hard limits for that particular resource (RLIMIT_CPU), and then set them using the number of seconds specified by the parameter and the hard limit retrieved previously. Finally, if the CPU runs longer than the limit, we signal system exit. In terms of memory usage, we retrieve the soft and hard limits again and set it using the setrlimit with the size parameter and the hard limit retrieved earlier.
Controls what can/cannot be imported
Some languages have very obvious mechanisms for exporting members (variables, methods, interfaces), such as Golang, where only members starting with capital letters are exported. However, in Python, all members are exported (unless we use "all"):
def foo(): pass def bar(): pass __all__ = ["bar"]
In the code above, we know that only the "bar" function is exported. Similarly, we can leave "all" empty so that nothing is exported, which causes an AttributeError when importing from this module.
Simple way to implement comparison operators
Implementing all the comparison operators (such as lt , le , gt , ge) for a class is cumbersome. Is there an easier way to do this? In this case, functools.total_ordering is a good helper:
Python tutorial/tool/method/puzzle +V: itz992from 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.