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

Counter

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
else:
result[fruit] += 1
print(result)
#{'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)
print(dict(c))
#{'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

sorted

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])
print(a)
# Output :[1, 2, 3, 4, 7, 9]
  • Invert tuples :
sorted((4,1,9,6),reverse=True)
print(a)
# 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))
print(a)
# Output :['pear', 'apple', 'banana', 'watermelon']

all

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
True
>>> all(['a', 'b', '', 'd']) # list list, There is an empty element
False
>>> all([0, 1,2, 3]) # list list, There exists a 0 The elements of
False
>>> all(('a', 'b', 'c', 'd')) # Tuples tuple, None of the elements are empty or 0
True
>>> all(('a', 'b', '', 'd')) # Tuples tuple, There is an empty element
False
>>> all((0, 1, 2, 3)) # Tuples tuple, There exists a 0 The elements of
False
>>> all([]) # An empty list
True
>>> all(()) # An empty tuple
True

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.

F-strings

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 :

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

stay F-strings We can also execute functions :

def power(x):
return x*x
x=4
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 ~

Python More related articles on built-in functions that are popular but very easy to use

  1. python Operators and expressions and common built-in functions in

    Knowledge content : 1. Operators and expressions 2.for\while A preliminary understanding 3. Common built-in functions One . Operators and expressions python Like other languages, most arithmetic operators are supported . Relational operator . Logical operators and bit operators , And there are and most ...

  2. Python Medium generator , iterator , And some commonly used built-in functions .

    Summary of knowledge points generator The essence of generator is iterator . iterator :Python Written tools provided in or obtained through data conversion . generator : We need to use it ourselves Python Code built There are three ways to create a generator : Through generator functions ...

  3. Python【map、reduce、filter】 Instructions for using built-in functions ( Reprint )

    from :http://www.blogjava.net/vagasnail/articles/301140.html?opt=admin introduce Python in map,reduce, and filter Inside ...

  4. Python【map、reduce、filter】 Instructions for using built-in functions

    . introduce Python in map,reduce, and filter Methods of built-in functions One :map map(...) map(function, sequence[, sequence, ...]) -& ...

  5. python The built-in functions learned by tribal brush topic treasure

    Recently joined python tribe , I think the brush inside is very interesting , Have fun , You know a lot of built-in functions that you didn't know before , And then I feel like I can't remember , So start showing it 1.divmod(a,b): take a Divide b The quotient and the remainder of , Efficacy is equivalent to ...

  6. python introduction ( Two ):isinstance、 Built in functions 、 Common operations, etc

    1.    isinstance( Variable name , type )                           # Judge what kind of ps: Only two parameters are supported , Input 3 An error will be reported for each parameter >>> isin ...

  7. python The basic chapter 14 Programmer expression Built in functions

    Yesterday's review     Iteratable object :        The interior contains __iter__ Method is iteratable object .        Iteratable object cannot take value , Because it doesn't contain __next__ Method .     Iteratable object ---> ...

  8. Python Grammar quick check : 1. Data types and built-in functions

    Return directory (1) Common built-in data types classification Type the name describe Numbers int Integers float Floating point numbers complex The plural bool Boolean value Sequence str character string ( Immutable sequence ) list list tuple ...

  9. Oracle in REGEXP_SUBSTR And other built-in functions that support regular expressions

    Oracle in REGEXP_SUBSTR Function instructions : The title is as follows : stay oracle in , Use a statement to implement '17,20,23' Split into '17','20','23' Set . REGEXP_SUBSTR Function lattice ...

  10. python The built-in functions learned by tribal brush topic treasure ( Two )

    I feel that there is an advantage in brushing the title , Maybe it's not good either , The answer has to be the real output value , That is to say, the string should be output aaaa When , The answer must be written as the value returned on the interface , namely 'aaaa'. It's good for memorizing the return value type , however .... It's too complicated 1 ...

Random recommendation

  1. Intent Jump pass list aggregate

    The first List<> Change it to ArrayList<> ArrayList<Good> list=new ArrayList<Good>(); Intent int ...

  2. datatables Parameters, ( turn )

    //@translator codepiano //@blog codepiano //@email [email protected] // Tried to translate , It's hard to avoid mistakes , Welcome to email us ...

  3. HDU 2202 The largest triangle

    Answer key : First calculate the convex hull , Then enumerate the points on the convex hull to calculate #include <cstdio> #include <cmath> #include <cstdlib> #incl ...

  4. Once and for all UAC problem ( modify QMAKE_LFLAGS_EXE Set up )

    If your program is running in an open UAC In the protected system , And your program doesn't " shield " Words , The program will always be blocked by all kinds of obstacles , For example, reading and writing documents , Write registry, etc . With " shield " Then there won't be some ...

  5. Ionic2 + Angular4 + JSSDK Summary of some problems in development

    prospects At present, WeChat official account development is quite hot. , The customer requests that his system have official account number. , It's already a very common need . The official account can facilitate the stakeholder to view information and interact with each other. , It is also very convenient to enter some data that is not easy to enter on the computer , ...

  6. .NET Garbage collection mechanism ( Two )

    One .GC The necessity of 1. Application operations on resources , It is usually simply divided into the following steps : Allocate memory for the corresponding resource → Initialize memory → Use resources  → Cleaning up resources  → Free memory . 2. Application to resource ( Memory usage ) The way of management , Common one ...

  7. Sudoku games js

    The rules : Players need to 9×9 Known number on disk , Infer the number of all remaining spaces : Make sure every line , Each column , The number of each palace just contains 1-9, And don't repeat . One . step : Make a grid ——  Generate 9×9 Numbers that meet the rules ——  Leave it empty ...

  8. centOS6.0 virtual machine ip To configure

    1. First, use the virtual machine to install centOS6.0 System 2. Virtual machine network configuration :( Choose bridge mode ) 3. First step : First, turn off the firewall 1. Remove fire services from the startup list #chkconfig --del iptables # ...

  9. EF Connect MySql database

    Windows If you want to EF Connect MySql, First install two applications mysql-connector-net-6.8.8.msimysql-for-visualstudio-1.2.7.msi The project needs two more ...

  10. [ turn ] To tell you the truth , All of you here can't write at all Java!

    Introduction since 2013 Years after graduation , This year is the first time I have worked 4 A year , Always doing Java Related work , Finally have time to sit down , Write an article about Java An article on writing method , Let's explore if you are really a Java The programmer , that ...