Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the advanced Python skills?

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "what are the advanced Python skills", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what are the advanced Python skills"?

1. Sort objects by multiple key values

Suppose you want to sort the following dictionary list:

People = [{'name':' John', "age": 64}, {'name':' Janet', "age": 34}, {'name':' Ed', "age": 24}, {'name':' Sara', "age": 64}, {'name':' John', "age": 32}, {'name':' Jane', "age": 34} {'name':' John', "age": 99},]

Sort not only by name or age, but also by both fields. In SQL, the query would look like this:

SELECT * FROM people ORDER by name, age

In fact, the solution to this problem can be very simple, and Python ensures that the sort function provides a stable sort order, which means that more similar items will retain their original order. To sort by name and age, you can do this:

Import operator people.sort (key=operator.itemgetter ('age')) people.sort (key=operator.itemgetter (' name'))

Pay attention to how to reverse the order. Sort by age first, then by name, and use operator.itemgetter () to get the age and name fields from each dictionary in the list, so you'll get the results you want:

[{'name':' Ed', 'age': 24}, {' name': 'Jane',' age': 34}, {'name':' Janet','age': 34}, {'name':' John', 'age': 32}, {' name': 'John',' age': 64}, {'name':' John', 'age': 99}, {' name': 'Sara' 'age': 64}]

The name is the main sort item, and if the name is the same, it is sorted by age. Therefore, all John are grouped together by age.

two。 Data category

Since version 3.7, Python has been able to provide data categories. It has more advantages than regular classes or other alternatives, such as returning multiple values or dictionaries:

Data classes require very little code

Data classes can be compared because _ _ eq__ can implement this function

Data classes require type hints, reducing the possibility of errors

You can easily print data classes for debugging, because _ _ repr__ can achieve this function

This is an example of a working data class:

From dataclasses import dataclass @ dataclass classCard: rank: str suit: str card=Card ("Q" "hearts") print (card = = card) # True print (card.rank) #'Q' print (card) Card (rank='Q', suit='hearts')

3. List derivation

List derivation can replace annoying loops in list filling, and its basic syntax is

[expression for item in list if conditional]

Let's look at a very basic example of populating a list with a sequence of numbers:

Mylist = [i for i inrange (10)] print (mylist) # [0, 1, 2, 3, 4,5,6,7,8,9]

Because you can use expressions, you can also do some mathematical operations:

Squares = [x**2for x inrange (10)] print (squares) # [0,1,4,9 people 16, 25, 36, 49, 64, 81]

You can even call external functions:

Defsome_function (a): return (a + 5) / 2 my_formula= [some_function (I) for i inrange (10)] print (my_formula) # [2.5,3.0 dint 3.5,4.0 4.5, 5.0, 5.5, 6.0, 6.5, 7.0]

Finally, you can use the if function to filter the list. In this case, only values that are divisible by 2 are retained:

Filtered = [i for i inrange (20) if I% 2 games 0] print (filtered) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

4. Check the memory usage of an object

Use sys.getsizeof () to check the memory usage of an object:

Import sys mylist = range (0, 10000) print (sys.getsizeof (mylist)) # 48

Why is this huge list only 48 bytes? This is because the class returned by the range function appears as a list. Compared with using the actual number list, the storage efficiency of the number sequence is much higher. We can use list derivation to create a list of actual numbers in the same range:

Import sys myreallist = [x for x inrange (0, 10000)] print (sys.getsizeof (myreallist)) # 87632

By using sys.getsizeof (), we can learn more about Python and memory usage.

5. Find the values that appear most frequently

To find the values that appear most frequently in a list or string:

Test = [1,2,3,4,2,2,3,1,4,4] print (max (set (test), key = test.count)) # 4

Max () returns the maximum value in the list. The key parameter takes a single parameter function to customize the sort order, in this case test.count, which applies to each item on the iterator.

Test.count is a built-in feature of list. It takes a parameter and calculates the number of occurrences of that parameter. So test.count (1) will return 2 and test.count (4) will return 4.

Set (test) returns all unique values in test, so {1, 2, 3, 4}

Then this line of code will accept all the unique values of test, that is, {1, 2, 3, 4}. Next, max will apply the list.count function to it and return the maximum value.

There is a more effective way:

From collections import Counter Counter (test). Most_common (1) # [4: 4]

6. Property package

You can use attrs instead of data classes, and choose attrs for two reasons:

The version of Python used is higher than 3.7

Want more features

The Theattrs package supports all major Python versions, including CPython 2.7 and PyPy. Some attrs can provide supernormal data classes such as validators and converters. Take a look at some sample code:

Attrs classPerson (object): name = attrib (default='John') surname = attrib (default='Doe') age = attrib (init=False) p=Person () print (p) p=Person ('Bill' 'Gates') p.age=60 print (p) # Output: # Person (name='John', surname='Doe',age=NOTHING) # Person (name='Bill', surname='Gates', age=60)

In fact, the authors of attrs are already using PEP that introduces data classes. Data classes are deliberately kept simpler and easier to understand, while attrs provides all the features you might need.

7. Merge Dictionary (Python3.5+)

Dict1 = {'averse: 1,' baked: 2} dict2= {'baked dict1 3,' cased: 4} merged= {* * dict1, * * dict2} print (merged) # {'Awesome: 1,' baked: 3, 'cased: 4}

If there are overlapping keys, the keys in the first dictionary will be overwritten. In Python 3.9, merge dictionaries become more concise. The merge in Python 3.9 above can be rewritten as follows:

Merged = dict1 | dict2

8. Return multiple values

Functions in Python can return multiple variables without dictionaries, lists, and classes. It works as follows:

Defget_user (id): # fetch user from database #.... Return name, birthdate name, birthdate = get_user (4)

This is a limited return value, but anything with more than three values should be put into a (data) class.

At this point, I believe you have a deeper understanding of "what advanced Python skills". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report