current position:Home>A popular but very easy-to-use built-in function in Python

A popular but very easy-to-use built-in function in Python

2022-02-02 11:46:27 Tsissan

Python There are many built-in functions in , Unlike print、len So well known , But they are extremely powerful , Using it well can greatly improve the code efficiency , At the same time, improve the simplicity of the code , Enhance readability


collections stay python The explanation in the official document is High-performance container datatypes, Direct Chinese translation to explain high-performance capacity data types . This module implements a specific target container , In order to provide Python Standard built-in containers dict , list , set , and tuple Alternative to . stay python3.10.1 It contains the following data types in total :

Container name brief introduction
namedtuple() Create factory functions for subclasses of named tuples
deque Similar list (list) The container of , Realize the quick addition at both ends (append) And pop up (pop)
ChainMap Similar to a dictionary (dict) The container class of , Assemble multiple maps into one view
Counter A subclass of a dictionary , Provides the counting function of hashable objects
OrderedDict A subclass of a dictionary , Saved the order in which they were added
defaultdict A subclass of a dictionary , Provides a factory function , Provide a default value for dictionary queries
UserDict Encapsulates the dictionary object , Simplified dictionary subclassing
UserList Encapsulates list objects , Simplified list subclassing
UserString Encapsulates a string object , Simplified string subclassing

among Counter It means counter in Chinese , That is, a data type we often use for Statistics , In the use of Counter Then we can make our code easier to read .Counter Class inheritance dict class , So it can use dict Methods in class

give an example

# Count the frequency of words 
fruits = ['apple', 'peach', 'apple', 'lemon', 'peach', 'peach']
result = {}
for fruit in fruits:
    if not result.get(fruit):
        result[fruit] = 1
        result[fruit] += 1
#{'apple': 2, 'peach': 3, 'lemon': 1}

Now let's use Counter How to achieve :

from collections import Counter
fruits = ['apple', 'peach', 'apple', 'lemon', 'peach', 'peach']
c = Counter(fruits)
#{'apple': 2, 'peach': 3, 'lemon': 1}

Obviously, the code is simpler , It's also easier to read and maintain .

  • elements()
    Returns an iterator , Each of these elements will repeat the times specified by the count value . Elements are returned in the order they first appear . If the count value of an element is less than 1,elements() It will be ignored .
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> sorted(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']
  • most_common([n])
    Return a list , It includes n The most common elements and their occurrences , Sort from high to low according to the degree of commonness . If n Omitted or omitted None,most_common() All elements in the counter will be returned . Elements with equal count values are sorted in the order in which they first appear :
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]

These two methods are Counter It's the most common method in , Other methods can refer to python3.10.1 Official documents

actual combat

Leetcode 1002. Find common characters
Here's an array of strings words, Please find out all in words A common character that appears in each string of ( Include repeating characters ), And return as an array . You can return the answers in any order .

 Input :words = ["bella", "label", "roller"]
 Output :["e", "l", "l"]

 Input :words = ["cool", "lock", "cook"]
 Output :["c", "o"]

See statistical characters , Typical can use Counter Perfect solution . The problem is to find out the characters contained in each element of the string list , First of all, you can use Counter Calculate the number of occurrences of each character of each element , Take the intersection in turn, and finally get the characters common to all elements , And then use it elements Output the number of occurrences of common characters

class Solution:
    def commonChars(self, words: List[str]) -> List[str]:
        from collections import Counter
        ans = Counter(words[0])
        for i in words[1:]:
            ans &= Counter(i)
        return list(ans.elements())

Submit a , Find out 83 Test cases take time 48ms, The speed is good


In processing data , We often use sorting operations , For example, list 、 Dictionaries 、 The element in the tuple is / Reverse order . And that's where it comes in sorted(), It can sort any iteratable object , And return to the list

  • Ascending the list :
a = sorted([2, 4, 3, 7, 1, 9])
#  Output :[1, 2, 3, 4, 7, 9]
  • Invert tuples :
#  Output :[9, 6, 4, 1]
  • Using parameter :key, According to custom rules , Sort by string length :
fruits = ['apple', 'watermelon', 'pear', 'banana']
a = sorted(fruits, key = lambda x : len(x))
#  Output :['pear', 'apple', 'banana', 'watermelon']


all() The function is used to determine a given iteratable parameter iterable Whether all elements in are TRUE, If it's a return True, Otherwise return to False. Except that the elements are 0、 empty 、None、False Outside is True. Be careful : An empty tuple 、 The empty list returns a value of True.

>>> all(['a', 'b', 'c', 'd'])  #  list list, None of the elements are empty or 0
>>> all(['a', 'b', '', 'd'])   #  list list, There is an empty element 
>>> all([0, 1,2, 3])          #  list list, There exists a 0 The elements of 
>>> all(('a', 'b', 'c', 'd'))  #  Tuples tuple, None of the elements are empty or 0
>>> all(('a', 'b', '', 'd'))   #  Tuples tuple, There is an empty element 
>>> all((0, 1, 2, 3))          #  Tuples tuple, There exists a 0 The elements of 
>>> all([])             #  An empty list 
>>> all(())             #  An empty tuple 

any The function is exactly the same as all The function is the opposite : Judge a tuple perhaps list Whether all are empty ,0,False. If all are empty ,0,False, Then return to False; If not all are empty , Then return to True.


stay python3.6.2 In the version ,PEP 498 A new string format mechanism is proposed , go by the name of “ String interpolation ” Or a more common form of address is F-strings,F-strings Provides a clear and convenient way to python Expressions are embedded in strings for formatting :

print(f'{s1} {s2}!')
# Hello World!

stay F-strings We can also execute functions :

def power(x):
  return x*x
print(f'{x} * {x} = {power(x)}')
# 4 * 4 = 16

and F-strings It runs very fast , Than traditional %-string and str.format() Both of these formatting methods are much faster , It's also easier to write .

This article mainly explains python Several popular but useful functions , More will be updated in the future ~

copyright notice
author[Tsissan],Please bring the original link to reprint, thank you.

Random recommended