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 useful built-in functions in Python

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Editor to share with you what are the built-in functions that are easy to use in Python, I believe most people don't know much about it, so share this article for your reference. I hope you can learn a lot after reading this article. Let's learn about it together.

Counter, an unpopular but easy-to-use built-in function in Python, gives an example of sortedallF-strings.

There are many built-in functions in Python, which are not as well known as print and len, but their functions are so powerful that they can greatly improve code efficiency, simplicity and readability.

Counter

Collections is interpreted as High-performance container datatypes in the official python documentation, which translates directly into Chinese to interpret high-performance capacity data types. This module implements specific containers to provide alternatives to the Python standard built-in containers dict, list, set, and tuple. In total, it contains the following data types in python3.10.1:

About container name namedtuple () creates a factory function of named tuple subclass deque similar to list (list) container, which quickly adds (append) and pops (pop) ChainMap like dictionary (dict) container classes at both ends, aggregates multiple mappings into subclasses of Counter dictionaries in one view, provides subclasses of hashable objects counting function OrderedDict dictionaries, and saves subclasses of the sequential defaultdict dictionaries in which they are added Provides a factory function to provide a default value for dictionary queries UserDict encapsulates dictionary objects, simplifies dictionary subclassing UserList encapsulates list objects, simplifies list subclassing UserString encapsulates string objects, simplifies string subclassing

Counter in Chinese means counter, which is a data type that we often use for statistics, which can make our code easier to read after using Counter. The Counter class inherits the dict class, so it can use the methods in the dict class

For example # Statistical word frequency fruits = ['apple',' peach', 'apple',' lemon', 'peach',' peach'] result = {} for fruit in fruits: if not result.get (fruit): result [fruit] = 1 else: result [fruit] + = 1print (result) # {'apple': 2,' peach': 3, 'lemon': 1}

Let's see how to implement it with Counter.

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

Obviously the code is simpler and easier to read and maintain.

Elements ()

Returns an iterator where each element will repeat the number of times specified by the count value. Elements are returned in the order in which they first appear. If the count of an element is less than 1, the element () will ignore it.

> c = Counter (axi4, baux2, cyste0, dystromel2) > sorted (c.elements ()) ['axiao,' axiang, 'axiang,' baked,'b']

Most_common ([n])

Returns a list of the n most common elements and the number of occurrences, sorted by frequency from highest to lowest. If n is omitted or is None,most_common (), all elements in the counter are returned. Elements with equal count values are sorted in the order in which they first appear:

These two methods are the most commonly used methods in Counter. For other methods, please refer to the official python3.10.1 documentation.

Actual combat

Leetcode 1002. Find common characters

To give you an array of strings words, please find out all the common characters (including repeating characters) that appear in each string of words and return them 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"]

When you see statistical characters, you can typically solve them perfectly with Counter. This problem is to find out the characters contained in each element in the string list. First, you can use Counter to calculate the number of times each character appears in each element, take the intersection in turn, and finally get the common characters of all elements, and then use elements to output the number 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 it and find that 83 test cases are time-consuming 48ms, and the speed is good.

Sorted

In the process of processing data, we often use sorting operations, such as positive / reverse sorting of elements in lists, dictionaries, and tuples. At this point, you need to use sorted (), which can sort any iterable object and return a list

To ascend the list:

A = sorted ([2,4,3,7,1,9]) print (a) # output: [1,2,3,4,7,9]

Reverse operation on tuples:

Sorted, reverse=True) print (a) # output: [9pr 6, 4je 1]

Use the parameter: key, sort by string length according to the custom rule:

Fruits = ['apple',' watermelon', 'pear',' banana'] a = sorted (fruits, key = lambda x: len (x)) print (a) # output: ['pear',' apple', 'banana',' watermelon'] all

The all () function is used to determine whether all elements in the given iterable parameter iterable are TRUE, and if True is returned, False is returned. Elements are True except for 0, null, None, and False. Note: the return value of empty tuple and empty list is True.

> all (['await,' baked, 'cased,' d']) # list list, none of the elements are empty or 0True > all (['await,' baked,'','d']) # list list, there is an empty element False > all ([0,1 Magne2, 3]) # list list There is an element False > all ('axie,' baked, 'cased,' d')) # tuple tuple, none of the elements are empty or 0True > all (('ajar,' baked,'','d')) # tuple tuple, there is an empty element False > all ((0,1,2,3)) # tuple tuple There is an element False > all ([]) # empty list True > all (()) # empty tuple True

The any function is just the opposite of the all function: to determine whether a tuple or list is all empty, zero false. Returns False; if it is all empty, 0gall false, or True if it is not all empty.

F-strings

In the python3.6.2 version, PEP 498 proposes a new string formatting mechanism, called "string interpolation" or, more commonly, FripstringsFormattering. FripstringsFormatting provides a clear and convenient way to embed python expressions into strings for formatting:

> all (['await,' baked, 'cased,' d']) # list list, none of the elements are empty or 0True > all (['await,' baked,'','d']) # list list, there is an empty element False > all ([0,1 Magne2, 3]) # list list There is an element False > all ('axie,' baked, 'cased,' d')) # tuple tuple, none of the elements are empty or 0True > all (('ajar,' baked,'','d')) # tuple tuple, there is an empty element False > all ((0,1,2,3)) # tuple tuple There is an element False > all ([]) # empty list True > all (()) # empty tuple True

We can also execute functions in F-strings:

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

And F-strings runs very fast, much faster and easier to write than the traditional%-string and str.format () formatting methods.

These are all the contents of the article "what are the useful built-in functions in Python?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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