【Python 零基础入门】常用内置函数 再探

【Python 零基础入门】内容补充 1 常用内置函数

  • Python 简介
  • 为什么要学习内置函数
  • 集合操作
    • len(): 计算长度
    • sorted(): 排序
    • all(): 检查所有元素
    • any(): 检查任一元素
    • filter(): 过滤元素
    • map(): 应用函数
    • zip(): 组合元素
  • 文件操作和输入输出
    • open(): 打开文件
    • read(): 读取文件
    • write(): 写入文件
    • input(): 获取用户输入
    • print(): 打印输出
    • format(): 格式化字符串
  • 错误和异常处理
    • try expert: 异常捕获
    • finally: 清理操作
    • raise: 触发异常
    • assert: 断言
    • with: 上下文管理

Python 简介

Python 是一种解释性, 高级和通用的变成语言. Python 由 Guido van Rossum 创建并 1991 年首次发布. Python 的设计强调代码的可读性, 其雨大允许我们使用相较于 C++ 或 Java 更少的代码表达概念. Python 使得变成变得更简单, 更快捷. 下面就跟着小白我来一起看一下 Python 常用的内置函数.

Python 内置函数

为什么要学习内置函数

Python 内置函数 (Built-In Function) 是 Python 解释器直接提供的函数, 相较于别的 Python 函数, 无需导入任何模块即可使用. 熟悉掌握 Python 的内置函数不仅可以帮助我们快速的完成常见的变成任务, 还可以使得我们的代码更加简洁, 易读.

集合操作

在上一部分的内容中, 我们介绍了数据类型转换函数以及数学运算相关的内置函数. 现在我们来探讨 Python 中用于处理集合的内置函数.

Python 集合操作

len(): 计算长度

len()函数返回对象 (字符, 列表, 元组等) 长度或项目个数.

格式:

length = len(s)

例子:

my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print("数组:", my_list, "长度:", length)

输出结果:

数组: [1, 2, 3, 4, 5] 长度: 5

sorted(): 排序

sorted()函数返回一个排序后的列表.

例子:

original_list= [1, 3, 5, 2, 4]
sorted_list = sorted(original_list)
print("原始数组:", original_list)
print("排序后的数组:", sorted_list)

输出结果:

原始数组: [1, 3, 5, 2, 4]
排序后的数组: [1, 2, 3, 4, 5]

all(): 检查所有元素

all()函数用于判断给定的可迭代参数中的所有元素是否都为 True, 如果是, 返回 True, 否则返回 False.

例子:

my_list = [1, 3, 4, 5]
result = all(my_list)
print(result)

输出结果:

True

any(): 检查任一元素

any()函数用于判断给定的可迭代参数是否全部为 False, 则返回 False, 如果有一个为 Ture, 则返回 True.

例子:

my_list = [0, 1, False]
result = any(my_list)
print(result)

输出结果:

True

常见用法:

# 列表推导式
numbers = [1, 3, 5, 7, 9]
result = any(n % 2 == 0 for n in numbers)  # False, 没有偶数
print(result)

result = any(n % 2 != 0 for n in numbers)  # True, 有奇数
print(result)

# 检查字符串中的字符
string = "Hello, World!"
result = any(c.isupper() for c in string)  # True, 'H' 和 'W' 是大写字母
print(result)

result = any(c.isdigit() for c in string)  # False, 没有数字
print(result)

输出结果:

False
True
True
False

filter(): 过滤元素

filter(): 函数用于过滤序列, 过滤掉不符合条件的元素, 返回一个迭代对象, 如果要转换为列表, 可以使用list()来转换.

numbers = [-3, -2, -1, 1, 2, 3]
less_than_zero = filter(lambda x: x < 0, numbers)
print(list(less_than_zero))

map(): 应用函数

map()函数根据提供的函数对指定序列做映射.

例子:

# 列表平方
numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x**2, numbers)
print(list(squared))

# 列表对应位置相加
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = map(lambda x,y: x+y, list1, list2)
print(list(result))

输出结果:

[1, 4, 9, 16, 25]
[5, 7, 9]

zip(): 组合元素

zip()函数用于将可迭代对象作为参数,

例子:

numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
zipped = zip(numbers, letters)
print(list(zipped)) 

输出结果:

[(1, 'a'), (2, 'b'), (3, 'c')]

常用方法:

# 创建字典
keys = ['name', 'age', 'gender']
values = ['我是小白呀', 18, 'Female']
dictionary = dict(zip(keys, values))
print(dictionary)

# 遍历俩列表
meals = ['早饭', '中饭', '晚饭']
foods = ['皮蛋瘦肉粥', '雪菜肉丝面', '黄焖鸡米饭']
for meal, food in zip(meals, foods):
    print(f'{meal} 吃了 {food}')

输出结果:

{'name': '我是小白呀', 'age': 18, 'gender': 'Female'}
早饭吃了: 皮蛋瘦肉粥
中饭吃了: 雪菜肉丝面
晚饭吃了: 黄焖鸡米饭

文件操作和输入输出

现在, 小白我带大家来探讨一下 Python 中用于处理文件和输入输出的内置函数.

open(): 打开文件

open(): 函数用于打开一个文件, 并返回文件对象.

例子:

# 打开文件用于读取
f = open('example.txt', 'r') 

# 读取文件内容
content = f.read()

# 关闭文件
f.close()  

read(): 读取文件

read()方法用于文件读取指定的字节数, 如果未给定未负责读取所有.

格式:

file.read(size)

参数:

  • size: 字节数

例子:

# 打开文件用于读取
f = open('example.txt', 'r')

# 读取前 10 个字符
content = f.read(10)

# 关闭文件
f.close()

write(): 写入文件

write()方法用于向文件中写入指定字符串.

例子:

# 打开文件
f = open('example.txt', 'w')

# 写入字符串
f.write('Hello, World!')

# 关闭文件
f.close()

input(): 获取用户输入

input()函数可以帮助我们获取输入流 (Input Stream).

例子:

name = input('请输入名字: ')
print('你好, ' + name + '!')

输出结果:

请输入名字: 我是小白呀
你好, 我是小白呀!

print(): 打印输出

print()函数用于将信息输出到控制台, 即输出流 (Output Stream).

例子:

# 输出
print('Hello World')

# 多个输出 (中间空格)
print('Hello World', '123')

# 换行输出
print('Hello World', '123', sep="\n")

输出结果:

Hello World
Hello World 123
Hello World
123

format(): 格式化字符串

format()函数用于格式化字符串.

例子:

name = "World"
message = "Hello, {}!".format(name)
print(message)

输出结果:

Hello, World!

错误和异常处理

我们来探讨一下 Python 中处理错误和异常的内置函数 (Build-In Function)

try expert: 异常捕获

tryexcept可以帮助我们是吸纳异常处理.

例子:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("不能除以 0 哦!")

输出结果:

不能除以 0 哦!

finally: 清理操作

finally语句用于无论是否发生异常都要执行的代码块, 通常用于资源清理操作.

例子:

try:
    f = open('example.txt', 'r')
    content = f.read()
except FileNotFoundError:
    print("File not found!")
finally:
    f.close()

raise: 触发异常

raise语句用于触发一个异常.

例子:

x = -1
if x < 0:
    raise ValueError("x 不能为负")

输出结果:

Traceback (most recent call last):
  File "C:\Users\Windows\Desktop\Python 基础\文件操作和输入输出.py", line 13, in <module>
    raise ValueError("x 不能为负")
ValueError: x 不能为负

assert: 断言

assert语句用于在程序中设置检查点, 当条件为 False 时触发异常.

例子:

x = -2
assert x > 0, "x must be positive"

输出结果:

Traceback (most recent call last):
  File "C:\Users\Windows\Desktop\Python 基础\文件操作和输入输出.py", line 17, in <module>
    assert x > 0, "x must be positive"
AssertionError: x must be positive

with: 上下文管理

with语句用于简化资源管理 (如文件读写), 它囧确保资源在使用后被正确关闭.

例子:

with open('example.txt', 'r') as f:
    content = f.read()

当我们使用with语句打开文件时, Python 会确保文件在with代码块执行完成后被正确关闭, 即使在代码中发生了异常也是如此. 我们无需使用 f.close() 释放资源.

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2023年11月22日
下一篇 2023年11月22日

相关推荐