← 返回首页

python函数进阶

📖 正文内容

iter()函数转换为迭代器

my_string="asdfsfewffwe" my_iter=iter(my_string)    for i in my_iter:      print(i)
该代码定义了一个字符串my_string并使用iter()函数将其转换为一个迭代器my_iter。这个迭代器可以逐个遍历字符串中的字符。

range()函数生成数字序列

在Python中,range()函数用于生成一个数字序列,通常用于迭代。它接受一到三个参数:

start (可选): 序列的起始值(包含),默认是0。

stop: 序列的结束值(不包含)。

step: 序列中每个元素之间的步长,默认是1。


range()函数的基本语法如下:

range(stop)

range(start, stop)

range(start, stop, step)

如果只提供stop参数,序列将从0开始,到stop - 1结束。

提供start参数会从指定的数值开始。

step参数可以设置为正数或负数,决定序列递增或递减的增量。

注意,step不能为0,因为这会导致无限循环。

# 生成 [0, 1, 2, 3] for i in range(4):     print(i) # 生成 [5, 6, 7] for i in range(5, 8):     print(i) # 生成 [3, 1, -1, -3] for i in range(3, 0, -2):     print(i)

map()函数

Python中map函数用来根据提供的函数(通过参数提供)对指定序列做映射。本质上来讲,map函数在Python中是一个迭代器生成函数。本文详解map函数的使用方法。
map() 函数的作用是:对序列 iterable 中每一个元素调用 function 函数,返回一个map对象实例。这个map对象本质上来讲是一个迭代器。

语法

map() 函数语法:

map(function, iterable, ...)

参数

  • function -- 函数
  • iterable -- 一个或多个序列

返回值

Python 3.x 返回迭代器。

>>> def square(x) :         # 计算平方数 ...     return x ** 2 ... >>> map(square, [1,2,3,4,5])    # 计算列表各个元素的平方 <map object at 0x100d3d550>     # 返回迭代器 >>> list(map(square, [1,2,3,4,5]))   # 使用 list() 转换为列表 [1, 4, 9, 16, 25] >>> list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))   # 使用 lambda 匿名函数 [1, 4, 9, 16, 25] >>>

map()函数+lambda表达式

bonuses = [100, 200, 300] iterator = map(lambda x: x*2, bonuses) print(list(iterator))  # 输出:[200, 400, 600]

map() 函数输入多个可迭代对象iterable

b1 = [100, 200, 300] b2 = [1, 2, 3] iterator = map(lambda x,y : x*y, b1, b2) print(list(iterator))  # 输出:[100, 400, 900]

查看返回的迭代器内容


  • 直接输出迭代器iterator,输出 map object 及其物理地址:
print(iterator)# 输出:
使用 for 循环对其进行遍历迭代器iterator:
for x in iterator:     print(x) # 输出: # 200 # 400 # 600
使用 list() 函数将迭代器转换为一个列表
print(list(iterator)) # 输出:[200, 400, 600]

map() 函数示例


示例一:使用 map() 函数操作字符串列表

以下示例使用 map() 函数对字符串列表中的每个元素进行首字母大写转换,然后返回一个新的列表:

names = ['david', 'peter', 'jenifer'] new_names = map(lambda name: name.capitalize(), names) print(list(new_names))
['David', 'Peter', 'Jenifer']

使用 map() 函数操作元组列表

假设存在以下由多个元组组成的购物车列表

我们需要计算每个产品的纳税额,税率为 10%。同时,我们需要将纳税额作为第三个元素添加到每个产品信息中。最终返回的列表如下:

为此,我们可以使用 map() 函数创建一个新的元素,将纳税额作为它的值:

carts = [['SmartPhone', 400],          ['Tablet', 450],          ['Laptop', 700]] TAX = 0.1 carts = map(lambda item: [item[0], item[1], item[1] * TAX], carts) print(list(carts))
[['SmartPhone', 400, 40.0],

['Tablet', 450, 45.0],

['Laptop', 700, 70.0]]


filter函数

在Python中,filter()是一个非常有用的内置函数,它能够根据指定的函数来筛选出可迭代对象中满足条件的元素,本文将从入门到精通,全面介绍filter()函数的用法和相关知识点

filter()函数的基本用法

filter()函数的基本语法如下:filter(function, iterable)
其中,function是一个用于判断的函数,iterable是一个可迭代对象,可以是列表、元组、集合或字符串等。filter()会将iterable中的每个元素依次传给function进行判断,返回满足条件的元素组成的迭代器。 让我们来看一个简单的例子,使用filter()函数过滤出列表中的偶数
# 定义一个函数,判断是否为偶数 def is_even(num):     return num % 2 == 0     # 待筛选的列表 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # 使用filter函数过滤出偶数 filtered_numbers = filter(is_even, numbers) # 将filter的结果转换为列表 result = list(filtered_numbers) print(result)  # 输出: [2, 4, 6, 8, 10]

使用Lambda表达式进一步简化代码

有时候,我们只需要使用一次性的简单函数进行筛选,此时可以使用Lambda表达式,从而省略单独定义函数的步骤,使代码更加简洁。以上面的例子为例,我们可以改写为:
# 待筛选的列表 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # 使用Lambda表达式过滤出偶数 filtered_numbers = filter(lambda x: x % 2 == 0, numbers) # 将filter的结果转换为列表 result = list(filtered_numbers) print(result)  # 输出: [2, 4, 6, 8, 10]

filter()函数的返回值是迭代器

需要注意的是,filter()函数的返回值是一个迭代器(Iterator),而不是列表。这意味着在进行一次迭代之后,迭代器中的元素就会被耗尽。如果需要多次访问结果,可以将它转换为列表或使用循环来逐个访问
# 待筛选的列表 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # 使用Lambda表达式过滤出偶数 filtered_numbers = filter(lambda x: x % 2 == 0, numbers) # 转换为列表 result_list = list(filtered_numbers) print(result_list)  # 输出: [2, 4, 6, 8, 10] # 再次尝试访问迭代器中的元素将为空 for num in filtered_numbers:     print(num)  # 不会输出任何内容

 过滤多个可迭代对象

filter()函数还可以同时过滤多个可迭代对象,此时传入的函数应该接受相应数量的参数。filter()会将多个可迭代对象中的元素按位置一一传入函数进行判断。
# 定义一个函数,判断两个数之和是否为偶数 def sum_is_even(a, b):     return (a + b) % 2 == 0     # 待筛选的列表 numbers1 = [1, 2, 3, 4, 5] numbers2 = [10, 20, 30, 40, 50] # 使用filter函数过滤出两个数之和为偶数 filtered_numbers = filter(sum_is_even, numbers1, numbers2) # 将filter的结果转换为列表 result = list(filtered_numbers) print(result)  # 输出: [3, 5]

使用None作为判断函数

在某些情况下,我们可能希望直接使用filter()函数来过滤掉可迭代对象中的一些"假值",例如空字符串、零等。此时,可以将filter()的函数参数设置为None,filter()函数会自动过滤掉那些判断为假的元素。
# 待筛选的列表,包含一些空字符串和非空字符串 words = ["hello", "", "world", " ", "python", ""] # 使用filter函数过滤掉空字符串 filtered_words = filter(None, words) # 将filter的结果转换为列表 result = list(filtered_words) print(result)  # 输出: ["hello", "world", " ", "python"]

综合示例:筛选出年龄大于等于18岁的成年人

下面我们来看一个综合示例,通过filter()函数从一个字典列表中筛选出年龄大于等于18岁的成年人。
# 待筛选的字典列表,每个字典包含姓名和年龄信息 people = [     {"name": "Alice", "age": 25},     {"name": "Bob", "age": 17},     {"name": "Charlie", "age": 19},     {"name": "David", "age": 15},     {"name": "Eva", "age": 22}, ] # 定义一个函数,判断是否为成年人(年龄大于等于18岁) def is_adult(person):     return person["age"] >= 18 # 使用filter函数过滤出成年人 adults = filter(is_adult, people) # 将filter的结果转换为列表 adults_list = list(adults) print(adults_list)  # 输出: [{'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 19}, {'name': 'Eva', 'age': 22}]

reduce() 函数对参数序列中元素进行累积

函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。
需要引入 functools 模块来调用 reduce() 函数
from functools import reduce

reduce(function, iterable[, initializer])
返回函数计算结果
#!/usr/bin/python from functools import reduce def add(x, y) :            # 两数相加     return x + y sum1 = reduce(add, [1,2,3,4,5])   # 计算列表和:1+2+3+4+5 sum2 = reduce(lambda x, y: x+y, [1,2,3,4,5])  # 使用 lambda 匿名函数 print(sum1) print(sum2)

reduce用法

#对列表元素求和,如果不用reduce,我们一般常用的方法是for循环 def sum_func(arr):     if len(arr) <= 0:         return 0     else:         out = arr[0]         for v in arr[1:]:             out += v         return out a = [1, 2, 3, 4, 5] print(sum_func(a)) #可以看到,代码量比较多,不够优雅。如果使用reduce,那么代码将非常简洁 from functools import reduce a = [1, 2, 3, 4, 5] def add(x, y): return x + y print(reduce(add, a)) #输出结果为15
与内置函数mapfilter不一样的是,在性能方面,reduce相比较for循环来说没有优势,甚至在实际测试中reducefor循环更慢如果希望代码更优雅而不在意耗时,可以用reduce

set(集合)数据结构

集合(Set)是Python中一种重要的数据结构,它具有以下特点:

无序性:集合中的元素没有特定的顺序,不能通过索引访问,也不支持切片操作。这意味着集合中的元素排列是任意的,每次打印集合时,元素的顺序可能不同。

唯一性:集合中的元素必须是唯一的,即集合不包含重复的元素。当你尝试向集合中添加一个已经存在的元素时,该操作不会改变集合。

可变性:集合本身是可变的,意味着你可以添加或删除其中的元素,但集合中的单个元素如果是不可变类型(如整数、浮点数、字符串、元组等),则这些元素不可更改。

基于哈希表:Python集合底层基于哈希表实现,这使得集合能够高效地进行成员检查、插入和删除操作。

创建集合

使用大括号 {} 直接创建,例如:my_set = {1, 2, 3}

使用 set() 函数创建,例如:my_set = set([1, 2, 3]) 或 my_set = set("abc")

常用操作

添加元素:my_set.add(element)

删除元素:my_set.remove(element) 或 my_set.discard(element)

集合运算:

并集:union_set = set1.union(set2) 或 union_set = set1 | set2

集合并集(Union)是指包含两个集合中所有不同元素的新集合。换句话说,如果你将两个集合合并,结果集合将包含至少出现在其中一个集合中的所有元素,而每个元素只出现一次。

set1 = {1, 2, 3} set2 = {2, 3, 4, 5} #union_set = set1 | set2这种方式也可以 union_set = set1.union(set2) print(union_set)  # 输出同样为: {1, 2, 3, 4, 5}

交集:intersection_set = set1.intersection(set2) 或 intersection_set = set1 & set2

set_A = {1, 2, 3, 4} set_B = {3, 4, 5, 6} # 使用 `&` 运算符 intersection_set = set_A & set_B # 或者使用 `intersection()` 方法 intersection_set = set_A.intersection(set_B) print(intersection_set)  # 输出: {3, 4}

差集:difference_set = set1.difference(set2) 或 difference_set = set1 - set2

set_A = {1, 2, 3, 4} set_B = {3, 4, 5, 6} # 使用 `-` 运算符 difference_set = set_A - set_B # 或者使用 `difference()` 方法 difference_set = set_A.difference(set_B) print(difference_set)  # 输出: {1, 2}

对称差集:symmetric_difference_set = set1.symmetric_difference(set2) 或 symmetric_difference_set = set1 ^ set2

set_A = {1, 2, 3, 4} set_B = {3, 4, 5, 6} # 使用 `^` 运算符 symmetric_difference_set = set_A ^ set_B # 或者使用 `symmetric_difference()` 方法 symmetric_difference_set = set_A.symmetric_difference(set_B) print(symmetric_difference_set)  # 输出: {1, 2, 5, 6}

判断子集和超集:is_subset = set1.issubset(set2),is_superset = set1.issuperset(set2)

集合更新:my_set.update(other_set),可以添加另一个集合的所有元素到当前集合中。

注意事项

集合中的元素必须是可哈希的,即不可变类型。因此,列表、字典等可变类型不能直接作为集合的元素。

集合不支持索引和切片,因为它是无序的。

集合在处理去重、集合运算等场景下非常有用,是Python编程中不可或缺的一部分。

三元运算符

Python中的三元运算符提供了一种简洁的方式来编写条件表达式,其语法不同于C、Java或JavaScript等语言中常见的条件 ? 表达式1 : 表达式2的形式。Python的三元运算符实际上是通过if-else语句的表达式形式来实现的,具体语法如下:
值_if_true if 条件 else 值_if_false
这里,条件是一个布尔表达式,如果条件为真(True),则计算并返回值_if_true;如果条件为假(False),则计算并返回值_if_false。
a = 10 b = 20 # 使用三元运算符决定最大值 max_value = a if a > b else b print(max_value)  # 输出: 20 # 更复杂的使用,包括在"值_if_true"或"值_if_false"中执行多条语句 result = "Positive" if x > 0 else ("Zero" if x == 0 else "Negative")

枚举Enumerate

enumerate 是Python内置的一个函数,用于在遍历列表、元组、字符串等可迭代对象时,同时提供元素的索引和值。它返回一个枚举对象,该对象可以被迭代,每次迭代返回一个包含索引和对应元素的元组。

下面是一个简单的使用 enumerate 的例子:

fruits = ['apple', 'banana', 'cherry'] for index, fruit in enumerate(fruits):     print(f"Index: {index}, Fruit: {fruit}") # Index: 0, Fruit: apple # Index: 1, Fruit: banana # Index: 2, Fruit: cherry
在这个例子中,enumerate(fruits) 返回一个枚举对象,每次迭代时,for 循环将索引 index 和对应的水果名称 fruit 分别赋值给变量 index 和 fruit。
enumerate 通常用于在需要同时访问元素索引和值的场景,比如在需要根据索引进行某些操作时,或者在重新排序或处理列表的顺序时。

open函数

Python 的 open() 函数用于打开文件,返回一个文件对象,你可以使用这个文件对象来读取、写入或追加文件内容
file_object = open(file_path, mode, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
参数说明:

file_path:要打开的文件的路径,可以是相对路径或绝对路径。

mode:打开文件的模式,常见的有:

'r':只读模式,文件必须存在。

'w':写入模式,如果文件存在,内容会被清空;不存在则创建。

'a':追加模式,文件存在则在末尾添加内容,不存在则创建。

'x':创建模式,如果文件不存在则创建,如果已存在则操作失败。

'b':二进制模式,可以与上述模式结合使用,如 'rb'、'wb'。

't':文本模式,默认模式,可以与上述模式结合使用,如 'rt'、'wt'。

'+':读写模式,可以同时读取和写入。

buffering:缓冲策略,通常设置为 -1 使用默认缓冲大小,或设置为具体缓冲区大小。

encoding:指定文件的字符编码,如 'utf-8'。

errors:指定处理编码错误的方式,如 'ignore'、'replace'。

newline:控制如何处理换行符,用于跨平台文件操作。

closefd:如果为 True(默认),关闭文件对象时会关闭底层的文件描述符。

opener:自定义的打开函数,可以用于提供更复杂的安全或权限处理。

# 打开一个文件并读取内容 with open('example.txt', 'r') as file:     content = file.read()     print(content) # 写入内容到文件 with open('example.txt', 'w') as file:     file.write('Hello, World!') # 追加内容到文件 with open('example.txt', 'a') as file:     file.write('\nThis is an appended line.')
使用 with 语句是推荐的做法,因为它会在操作完成后自动关闭文件,即使发生异常也会执行清理。不使用 with 语句时,需要手动调用 file.close() 来关闭文件。

sorted函数排序

sorted() 函数是Python中用于对可迭代对象进行排序的内置函数。它返回一个新的已排序的列表,不会改变原始数据
sorted(iterable, key=None, reverse=False)
参数说明:

iterable:需要排序的可迭代对象,如列表、元组、字符串等。

key(可选):一个函数,该函数接收一个元素并返回一个值,这个值将用于排序。例如,如果要基于元素的某个属性进行排序,可以提供一个函数来获取那个属性。

reverse(可选):一个布尔值,如果设为True,则进行降序排序,否则(默认)进行升序排序。

以下是一些使用sorted()函数的例子:

升序排序列表:

numbers = [5, 2, 9, 1, 5, 6] sorted_numbers = sorted(numbers) print(sorted_numbers)  # 输出: [1, 2, 5, 5, 6, 9]
降序排序
sorted_numbers_desc = sorted(numbers, reverse=True) print(sorted_numbers_desc)  # 输出: [9, 6, 5, 5, 2, 1]
使用key参数根据字符串长度排序:
words = ['apple', 'banana', 'cherry'] sorted_words = sorted(words, key=len) print(sorted_words)  # 输出: ['apple', 'cherry', 'banana']
根据字典值排序
my_dict = {'a': 3, 'b': 1, 'c': 2} sorted_dict_keys = sorted(my_dict, key=my_dict.get) print(sorted_dict_keys)  # 输出: ['b', 'c', 'a']
复杂排序,使用自定义函数:
data = [('John', 35), ('Alice', 27), ('Bob', 42)] sorted_data = sorted(data, key=lambda x: x[1]) print(sorted_data)  # 输出: [('Alice', 27), ('John', 35), ('Bob', 42)]
注意,sorted()函数返回的是一个新的列表,原始数据不会被改变。如果需要在原地排序列表,可以使用列表的sort()方法,它会直接修改原列表。

💡 示例代码

<div style='--en-codeblock:true;--en-blockId:El-aQ2qihaI;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>my_string="asdfsfewffwe"
my_iter=iter(my_string)    
for i in my_iter:    
  print(i)</div>

<div style='--en-codeblock:true;--en-blockId:OSI5QqXS0xR;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'># 生成 [0, 1, 2, 3]
for i in range(4):
    print(i)

# 生成 [5, 6, 7]
for i in range(5, 8):
    print(i)

# 生成 [3, 1, -1, -3]
for i in range(3, 0, -2):
    print(i)
</div>

<div style='--en-codeblock:true;--en-blockId:gk9iTGWwRdV;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>map(function, iterable, ...)</div>

<div style='--en-codeblock:true;--en-blockId:S80zTqU7O4g;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>&gt;&gt;&gt; def square(x) :         # 计算平方数
...     return x ** 2
... 
&gt;&gt;&gt; map(square, [1,2,3,4,5])    # 计算列表各个元素的平方
&lt;map object at 0x100d3d550&gt;     # 返回迭代器
&gt;&gt;&gt; list(map(square, [1,2,3,4,5]))   # 使用 list() 转换为列表
[1, 4, 9, 16, 25]
&gt;&gt;&gt; list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))   # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
&gt;&gt;&gt;</div>

<div style='--en-codeblock:true;--en-blockId:a7qXQ2vzokx;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>bonuses = [100, 200, 300]
iterator = map(lambda x: x*2, bonuses)
print(list(iterator))  # 输出:[200, 400, 600]
</div>

<div style='--en-codeblock:true;--en-blockId:yxFaQ-1_AUc;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>b1 = [100, 200, 300]
b2 = [1, 2, 3]

iterator = map(lambda x,y : x*y, b1, b2)
print(list(iterator))  # 输出:[100, 400, 900]
</div>

<div style='--en-codeblock:true;--en-blockId:dIZbRiKoeR4;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>print(iterator)# 输出:</div>

<div style='--en-codeblock:true;--en-blockId:7-mqSSD2lIz;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>for x in iterator:
    print(x)
# 输出:
# 200
# 400
# 600
</div>

<div style='--en-codeblock:true;--en-blockId:WcNuT2oEZJg;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>print(list(iterator))
# 输出:[200, 400, 600]
</div>

<div style='--en-codeblock:true;--en-blockId:hdUdRqTAw_0;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>names = ['david', 'peter', 'jenifer']
new_names = map(lambda name: name.capitalize(), names)
print(list(new_names))
</div>

<div style='--en-codeblock:true;--en-blockId:kE6vRGg7Opc;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>carts = [['SmartPhone', 400],
         ['Tablet', 450],
         ['Laptop', 700]]

TAX = 0.1
carts = map(lambda item: [item[0], item[1], item[1] * TAX], carts)

print(list(carts))</div>

<div style='--en-codeblock:true;--en-blockId:RG9xTe048Ar;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'># 定义一个函数,判断是否为偶数
def is_even(num):
    return num % 2 == 0
    # 待筛选的列表
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 使用filter函数过滤出偶数
filtered_numbers = filter(is_even, numbers)
# 将filter的结果转换为列表
result = list(filtered_numbers)
print(result)  # 输出: [2, 4, 6, 8, 10]</div>

<div style='--en-codeblock:true;--en-blockId:USPaSi57NMl;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'># 待筛选的列表
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 使用Lambda表达式过滤出偶数
filtered_numbers = filter(lambda x: x % 2 == 0, numbers)
# 将filter的结果转换为列表
result = list(filtered_numbers)
print(result)  # 输出: [2, 4, 6, 8, 10]</div>

<div style='--en-codeblock:true;--en-blockId:fbQZQ2Ymtbp;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'># 待筛选的列表
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 使用Lambda表达式过滤出偶数
filtered_numbers = filter(lambda x: x % 2 == 0, numbers)
# 转换为列表
result_list = list(filtered_numbers)
print(result_list)  # 输出: [2, 4, 6, 8, 10]
# 再次尝试访问迭代器中的元素将为空
for num in filtered_numbers:
    print(num)  # 不会输出任何内容</div>

<div style='--en-codeblock:true;--en-blockId:qU6zTyDmX6i;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'># 定义一个函数,判断两个数之和是否为偶数
def sum_is_even(a, b):
    return (a + b) % 2 == 0
    # 待筛选的列表
numbers1 = [1, 2, 3, 4, 5]
numbers2 = [10, 20, 30, 40, 50]
# 使用filter函数过滤出两个数之和为偶数
filtered_numbers = filter(sum_is_even, numbers1, numbers2)
# 将filter的结果转换为列表
result = list(filtered_numbers)
print(result)  # 输出: [3, 5]</div>

<div style='--en-codeblock:true;--en-blockId:wMXiT6gvmOZ;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'># 待筛选的列表,包含一些空字符串和非空字符串
words = ["hello", "", "world", " ", "python", ""]
# 使用filter函数过滤掉空字符串
filtered_words = filter(None, words)
# 将filter的结果转换为列表
result = list(filtered_words)
print(result)  # 输出: ["hello", "world", " ", "python"]</div>

<div style='--en-codeblock:true;--en-blockId:ky-vQWySzSs;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'># 待筛选的字典列表,每个字典包含姓名和年龄信息
people = [
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 17},
    {"name": "Charlie", "age": 19},
    {"name": "David", "age": 15},
    {"name": "Eva", "age": 22},
]
# 定义一个函数,判断是否为成年人(年龄大于等于18岁)
def is_adult(person):
    return person["age"] &gt;= 18
# 使用filter函数过滤出成年人
adults = filter(is_adult, people)
# 将filter的结果转换为列表
adults_list = list(adults)
print(adults_list)  # 输出: [{'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 19}, {'name': 'Eva', 'age': 22}]</div>

<div style='--en-codeblock:true;--en-blockId:do7eS2IUFef;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>#!/usr/bin/python
from functools import reduce

def add(x, y) :            # 两数相加
    return x + y
sum1 = reduce(add, [1,2,3,4,5])   # 计算列表和:1+2+3+4+5
sum2 = reduce(lambda x, y: x+y, [1,2,3,4,5])  # 使用 lambda 匿名函数
print(sum1)
print(sum2)</div>

<div style='--en-codeblock:true;--en-blockId:s3grTqY_BIG;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>#对列表元素求和,如果不用reduce,我们一般常用的方法是for循环
def sum_func(arr):
    if len(arr) &lt;= 0:
        return 0
    else:
        out = arr[0]
        for v in arr[1:]:
            out += v
        return out

a = [1, 2, 3, 4, 5]
print(sum_func(a))

#可以看到,代码量比较多,不够优雅。如果使用reduce,那么代码将非常简洁
from functools import reduce
a = [1, 2, 3, 4, 5]
def add(x, y): return x + y
print(reduce(add, a))

#输出结果为15</div>

<div style='--en-codeblock:true;--en-blockId:1AgIT-ymyHp;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>set1 = {1, 2, 3}
set2 = {2, 3, 4, 5}
#union_set = set1 | set2这种方式也可以
union_set = set1.union(set2)
print(union_set)  # 输出同样为: {1, 2, 3, 4, 5}

</div>

<div style='--en-codeblock:true;--en-blockId:evulRScLHgD;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>set_A = {1, 2, 3, 4}
set_B = {3, 4, 5, 6}

# 使用 `&amp;` 运算符
intersection_set = set_A &amp; set_B

# 或者使用 `intersection()` 方法
intersection_set = set_A.intersection(set_B)

print(intersection_set)  # 输出: {3, 4}
</div>

<div style='--en-codeblock:true;--en-blockId:cObVRSpdVKg;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>set_A = {1, 2, 3, 4}
set_B = {3, 4, 5, 6}

# 使用 `-` 运算符
difference_set = set_A - set_B

# 或者使用 `difference()` 方法
difference_set = set_A.difference(set_B)

print(difference_set)  # 输出: {1, 2}
</div>

<div style='--en-codeblock:true;--en-blockId:Bsp0RmGMWeR;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>set_A = {1, 2, 3, 4}
set_B = {3, 4, 5, 6}

# 使用 `^` 运算符
symmetric_difference_set = set_A ^ set_B

# 或者使用 `symmetric_difference()` 方法
symmetric_difference_set = set_A.symmetric_difference(set_B)

print(symmetric_difference_set)  # 输出: {1, 2, 5, 6}
</div>

<div style='--en-codeblock:true;--en-blockId:UOt4RqkODQc;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>a = 10
b = 20

# 使用三元运算符决定最大值
max_value = a if a &gt; b else b
print(max_value)  # 输出: 20

# 更复杂的使用,包括在"值_if_true"或"值_if_false"中执行多条语句
result = "Positive" if x &gt; 0 else ("Zero" if x == 0 else "Negative")
</div>

<div style='--en-codeblock:true;--en-blockId:jnvORWilAh1;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>fruits = ['apple', 'banana', 'cherry']

for index, fruit in enumerate(fruits):
    print(f"Index: {index}, Fruit: {fruit}")

# Index: 0, Fruit: apple
# Index: 1, Fruit: banana
# Index: 2, Fruit: cherry
</div>

<div style='--en-codeblock:true;--en-blockId:ePlaRKt6v8a;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>file_object = open(file_path, mode, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
</div>

<div style='--en-codeblock:true;--en-blockId:lUpvQmIcB9m;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'># 打开一个文件并读取内容
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

# 写入内容到文件
with open('example.txt', 'w') as file:
    file.write('Hello, World!')

# 追加内容到文件
with open('example.txt', 'a') as file:
    file.write('\nThis is an appended line.')
</div>

<div style='--en-codeblock:true;--en-blockId:C_wrSGwyFYi;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 输出: [1, 2, 5, 5, 6, 9]
</div>

<div style='--en-codeblock:true;--en-blockId:vodPReccfAy;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc)  # 输出: [9, 6, 5, 5, 2, 1]
</div>

<div style='--en-codeblock:true;--en-blockId:35IYTOu323n;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>words = ['apple', 'banana', 'cherry']
sorted_words = sorted(words, key=len)
print(sorted_words)  # 输出: ['apple', 'cherry', 'banana']
</div>

<div style='--en-codeblock:true;--en-blockId:JH8mSW3FeuA;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>my_dict = {'a': 3, 'b': 1, 'c': 2}
sorted_dict_keys = sorted(my_dict, key=my_dict.get)
print(sorted_dict_keys)  # 输出: ['b', 'c', 'a']
</div>

<div style='--en-codeblock:true;--en-blockId:Z9X2RORlZjE;--en-meta:{"title":"","lang":"Python","theme":"default","showLine":true,"lineWrap":false};box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial; margin-top: 6px;'>data = [('John', 35), ('Alice', 27), ('Bob', 42)]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)  # 输出: [('Alice', 27), ('John', 35), ('Bob', 42)]
</div>

💭 技巧提示

💡

📚 参考资料

💬 评论交流

👤
用户 A 2026-03-25

这个技巧很实用,感谢分享!