search
HomeBackend DevelopmentPython TutorialIntroduction to Python's common built-in functions

Introduction to Python's common built-in functions

Sep 07, 2017 am 09:42 AM
pythonintroducefunction

The so-called built-in functions can be used directly without import. The following article mainly introduces some common built-in functions for basic learning of Python. The article introduces them to you in great detail through sample codes. Friends who need them can refer to them. Let's follow the editor to learn together.

Preface

Python provides many built-in functions to handle many types. The function of these built-in functions is that they can often Perform similar operations on multiple types of objects, that is, operations common to multiple types of objects. I won’t go into more details below. Let’s take a look at the detailed introduction.

map()

The map() function accepts two parameters, one is a function and the other is an iterable object (Iterable), map Apply the passed function to each element of the iterable object in turn, and return the result as an iterator.

For example, there is a function f(x)=x^2 , and you want to apply this function to a list[1,2,3,4, 5,6,7,8,9]上:

Using a simple loop can achieve:


>>> def f(x):
...  return x * x
...
L = []
for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
 L.append(f(n))
print(L)

Using advanced Function map():


>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]

The result r is an iterator, and the iterator is a lazy sequence, passed list() The function lets it calculate the entire sequence and return a list.

If you want to convert all the numbers in this list into strings, use map(). It’s simple:


>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
['1', '2', '3', '4', '5', '6', '7', '8', '9']

Small exercise: Use the map() function to change the non-standard English name entered by the user into a standard name with the first letter capitalized and other lowercase letters. Input['adam', 'LISA', 'barT'],Output['Adam', 'Lisa', 'Bart']


def normalize(name):
  return name.capitalize()

 l1=["adam","LISA","barT"]
 l2=list(map(normalize,l1))
 print(l2)

reduce()

reduce()The function also accepts two parameters, one is a function and the other is Iterable object, reduce will perform cumulative calculation on the result of applying the passed function to each element of the iterable object. Then return the final result.

The effect is: reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

For example, convert the sequence [1,2,3,4,5] into an integer 12345:


>>> from functools import reduce
>>> def fn(x, y):
...  return x * 10 + y
...
>>> reduce(fn, [1, 2, 3, 4, 5])
12345

Small exercise: Write a prod() function that can accept a list and use reduce to calculate the product:


from functools import reduce
def pro (x,y):
  return x * y
 def prod(L):
  return reduce(pro,L)
 print(prod([1,3,5,7]))

map()andreduce()Comprehensive exercise: Write the str2float function to convert the string '123.456' into a floating point type 123.456


CHAR_TO_FLOAT = {
 '0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9, '.': -1
}
def str2float(s):
 nums = map(lambda ch:CHAR_TO_FLOAT[ch],s)
 point = 0
 def to_float(f,n):
   nonlocal point
   if n==-1:
    point =1
    return f
   if point ==0:
    return f*10+n
   else:
    point =point *10
    return f + n/point

 return reduce(to_float,nums,0)#第三个参数0是初始值,对应to_float中f

filter()

filter()The function is used to filter the sequence, filter() also accepts a function and a sequence, filter()Apply the passed function to each element in turn, and then decide whether to keep or discard the element based on whether the return value is True or False.

For example, delete even numbers in the list:


def is_odd(n):
 return n % 2 == 1

list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]

Small exercise: Use filter() to find prime numbers

One method of calculating prime numbers is the Ehrlich sieve method. Its algorithm is very simple to understand:

First, list all natural numbers starting from 2 and construct a sequence:

2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

Take the first number 2 of the sequence, which must be a prime number, and then use 2 to filter out the multiples of 2 in the sequence:

3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

Get the first number 3 of the new sequence, It must be a prime number, and then use 3 to filter out the multiples of 3 in the sequence:

5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

Take the first number 5 of the new sequence, and then use 5 to filter out the multiples of 5 in the sequence:

7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

Keep sifting and you can get all Prime number.

Use Python to implement this algorithm. First construct a period sequence starting from 3:


def _odd_iter(): 
n = 1
 while True:
  n = n + 2
  yield n
#这是一个生成器,并且是一个无线序列

Define a filtering function:


def _not_pisible(n):
 return lambda x: x % n > 0

Define a generator to continuously return the next prime number:


def primes():
 yield 2
 it = _odd_iter() # 初始序列
 while True:
  n = next(it) # 返回序列的第一个数
  yield n
  it = filter(_not_pisible(n), it) # 构造新序列

Print prime numbers within 100:


for n in primes():
 if n < 100:
  print(n)
 else:
  break

sorted()

Python’s built-in sorted() function can sort the list Sort:


>>> sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]

sorted() The function is also a higher-order function and can also accept a key function to implement custom sorting:


>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]

The function specified by key will act on each element of the list and be sorted according to the result returned by the key function.

默认情况下,对字符串排序,是按照ASCII的大小比较的,由于'Z'


>>> sorted([&#39;bob&#39;, &#39;about&#39;, &#39;Zoo&#39;, &#39;Credit&#39;], key=str.lower)
[&#39;about&#39;, &#39;bob&#39;, &#39;Credit&#39;, &#39;Zoo&#39;]

要进行反向排序,不必改动key函数,可以传入第三个参数reverse=True


>>> sorted([&#39;bob&#39;, &#39;about&#39;, &#39;Zoo&#39;, &#39;Credit&#39;], key=str.lower, reverse=True)
[&#39;Zoo&#39;, &#39;Credit&#39;, &#39;bob&#39;, &#39;about&#39;]

小练习:假设我们用一组tuple表示学生名字和成绩:L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] 。用sorted()对上述列表分别按c成绩从高到低排序:


L = [(&#39;Bob&#39;, 75), (&#39;Adam&#39;, 92), (&#39;Bart&#39;, 66), (&#39;Lisa&#39;, 88)]
def by_score(t):
 for i in t:
   return t[1]
L2=sorted(L,key= by_score)
print(L2)

运用匿名函数更简洁:


L2=sorted(L,key=lambda t:t[1])
print(L2)

The above is the detailed content of Introduction to Python's common built-in functions. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)