In this article, we will introduce 15 simple Python tips to help you keep things simple, efficient, and easy to understand.

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},]Copy the code

Not only do you sort it by name or age, but you also sort both fields simultaneously. In SQL, the query would look like this:

SELECT * FROM people ORDER by name, age
Copy the code

In fact, the solution to this problem can be quite simple. Python guarantees that sort provides a stable sort order, which also means that items that are more similar will retain their original order. To implement sorting by name and age, do the following:

import operator 
people.sort(key=operator.itemgetter('age')) 
people.sort(key=operator.itemgetter('name'))
Copy the code

Be careful how you reverse the order. First sort by age, then by name, and use operator.itemgetter() to get the age and name fields from each dictionary in the list, so you get the result 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}]Copy the code

The first name is the main sorting item, and if the names are the same, they are sorted by age. Therefore, all Johns are grouped together by age.

2. Data categories

Python has been able to provide data categories since version 3.7. It has many advantages over regular classes or alternative methods such as returning multiple values or dictionaries:

  1. Data classes require very little code
  2. Data classes can be compared because EQ can do this
  3. Data classes require type hints, reducing the possibility of errors
  4. You can easily print data classes for debugging, because __repr__ can do this

Here is an example of a data class at work:

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')
Copy the code

3. List derivation

List derivation can be used to replace annoying loops in list entries with the basic syntax

[ expression for item in list if conditional ]
Copy the code

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]
Copy the code

Because you can use expressions, you can also do some math:

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

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, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0]
Copy the code

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

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

4. Check the memory usage of the object

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

import sys 
     mylist =range(0.10000) 
   print(sys.getsizeof(mylist)) 
   # 48
Copy the code

The reason this large list is only 48 bytes long is because the range function returns classes that are represented as lists. A sequence of numbers is much more efficient to store than using an actual list of numbers. 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
Copy the code

We can learn more about Python and memory usage by using sys.getsizeof().

5. Look for the most frequent values

To find the most frequent values in a list or string:

test = [1.2.3.4.2.2.3.1.4.4.4] 
  print(max(set(test), key = test.count)) 
  # 4
Copy the code
  • Max () returns the maximum value in the list. The key argument takes a custom sort order from a single argument function, test.count in this case, that applies to each item on the iterator.
  • Test. count is a built-in feature of list. It takes a parameter and counts 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}

So in this line of code you will accept all the unique values of test, that is {1, 2, 3, 4}. Next, Max applies the list.count function to it and returns the maximum value.

There’s a more effective way:

from collections import Counter 
Counter(test).most_common(1) 
# [4:4)
Copy the code

6. Attribute package

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

  1. Python version later than 3.7 is used
  2. Want more features

Theattrs packages support all major Python releases, including CPython 2.7 and PyPy. Some ATTRs can provide hypergeneric 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)
Copy the code

In fact, the attrs authors are already using pePs that introduce data classes. Data classes are intentionally kept simpler and easier to understand, and ATTRs provides all the features you might need.

7. Merge dictionaries (Python3.5+)

dict1 = { 'a': 1.'b': 2 } 
  dict2= { 'b': 3.'c': 4 } 
  merged= { **dict1, **dict2 } 
  print (merged) 
  # {'a': 1, 'b':3, 'c': 4}
Copy the code

If there are overlapping keys, the keys in the first dictionary will be overwritten. In Python 3.9, merging dictionaries became even cleaner. The merge in Python 3.9 above can be rewritten as:

merged = dict1 | dict2
Copy the code

8. Return multiple values

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

defget_user(id) :# fetch user from database 
      #...
      return name, birthdate 
     name, birthdate =get_user(4)
Copy the code

This is a limited number of return values, but anything with more than three values should go into one (data) class.

9. Filter list elements

The use of the filter ()

The filter() function takes two arguments:

  1. The function object
  2. Iterable objects

Next we define a function and filter a list.

First we create a list and remove elements less than or equal to 3:

original_list = [ 1.2.3.4.5]# define list
  
Define the filter function
4 def filter_three(number) :5
  return number > 3
    
filtered = filter(filter_three, original_list)
filtered_list = list(filtered)
filtered_list
  
# (4, 5)
Copy the code

We define the list original_list. Then we define a function that takes the numeric parameter number, filter_three, and returns True if the value of the parameter passed is greater than 3, False if it is not. We define the filter object filtered, Filter () takes a function object as the first argument, and a list object as the second argument.

Similarly, list comprehensions can be used to filter list elements as an elegant way to generate and modify lists. Here’s how to do the same with list comprehensions:

original_list = [1.2.3.4.5]2
filtered_list = [ number for number in original_list if number > 3]# Introduce conditional judgment in list derivation
print(filtered_list)
  
# (4, 5)
Copy the code

10. Modify the list

The use of the map ()

The built-in map() function in Python makes it possible to apply a function to every element in an iterable.

For example, if we want to get the square of each element in a list object, we can use the map() function, as in the following example:

original_list = [1.2.3.4.5]
def square( number) :
    return number **2
squares =map(square, original_list)
squares_list = list( squares)
print(squares_list) 
  
#[1,4,9,16,25]
Copy the code

Similar to how filter() works, let’s see what happens:

First we defined original_list and the function square() that takes a numeric argument and returns its square value. Then we defined a map object squares, similar to filter(). The first argument map() takes is a function object, The second argument is the list object and finally we squares the Map object and we get the result we want.

Similarly, we can use the list derivation to accomplish the same task:

original_list = [1.2.3.4.5]
squares_list = [number ** 2for number in original_list]
print(squares_list)
  
#[1,4,9, 16,25]
Copy the code

11. Use zip() to combine lists

There are cases where we need to combine two or more lists together, which is very convenient to do with zip(). The zip() function takes multiple lists as arguments to get a one-to-one combination of elements at each location, as in the following example:

numbers = [ 1.2.3]
letters = [ 'a'.'b'.'c']
combined = zipNumbers, letters combined_list =list( combined)
print(combined_list)
for item in zip( numbers,letters ):
    print(item[0].'\t', item[1])
      
#[(1, 'a'), (2, 'b'), (3, 'c')]
#1 a
#2 b
#3 c
Copy the code

12. Reverse the list

A list in Python is an ordered data structure. As such, the order of the elements in a list is important. Sometimes we need to reverse the order of all the elements in a list.

original_list = [1.2.3.4.5]

reversed_list = original_list[ : : -1]

print('Before flipping:', original_list)
print('After flipping :', reversed_list)
  
[1,2,3,4,5]
[5,4,3,2,1]
Copy the code

13. Check the presence of elements in the list

We can use the in operator in cases where we want to check for the presence of an element in a list. For example, if we have a list of all the winning teams, we can query for the presence of a team, as in the following example:

games = [ 'Yankees '.'Yankees '.'Cubs '.'Blue Jays '.'Giants ']
def isin(Item, list_name) :
    if item in list_name: print(f"{item} is in the list! ")
    else: print(f"{item} is not in the list! ")

isin( 'Blue Jays ' , games)
isin( ' Angels', games)

#Blue Jays is in the list!
#Angels is not in the list!
Copy the code

14. Flatten the nested list

In some cases we may encounter nested lists where each element is a separate list. In this case we can use a list derivation to flatten the nested list, as in the following example of two levels of nesting:

nested_list = [[1.2.3], [4.5.6], [7.8.9]]

flat_list = [i for j in nested_list for i in j]

print(flat_list)

#[1,2,3,4,5,6,7,8,9]
Copy the code

Additional information:

PIP install dm-tree is a library designed to flatten out nested structures. It can flatten out nested lists at any level. The following is an example:

import tree

nested_list_2d = [[1.2.3], [4.5.6], [7.8.9]]

nested_list_3d = [[[1.2], [3.4]],
                          [[5.6], [7.8]],
                          [[9.10], [11.12]]]
                           
print(tree.flatten(nested_list_2d))
print(tree.flatten(nested_list_3d))

#[1,2,3,4,5,6,7,8,9]
#[1,2,3,4,5,6,7,,8, 9, 10, 11,12]
Copy the code

15. Check for uniqueness

If you want to see if all values in a list are unique, you can use Python’s set data structure features, such as the following example:

list1 = [ 1.2.3.4.5]
list2 = [1.1.2.3.4]

def isunique( 1) :
    if len(l) == len(set(l)) :
       print(the only!') eise: print(('Not only!') isunique(list1) isunique(list2) # # not only!Copy the code

I look forward to your three consecutive (likes, favorites, comments), your support is my continuous output of power, thank you.

① Interesting source code and learning experience ② tool installation package, installation video ③ than books convenient reading 300 e-books ④ professional answers to questions

Click to receive