Python 常用函数与方法详解
·
目录
1、split()
没有内容默认以空白分割
# 默认以空白字符分割
text = "hello world python"
result = text.split()
print(result) # ['hello', 'world', 'python']
指定分隔符:有一个字符串以该字符串进行分割
# 使用特定字符串作为分隔符
text = "apple,banana,orange,grape"
result = text.split(',')
print(result) # ['apple', 'banana', 'orange', 'grape']
# 限制分割次数
text = "one:two:three:four"
result = text.split(':', 2) # 只分割前两次
print(result) # ['one', 'two', 'three:four']
特殊情况
# 空字符串分割
text = ""
result = text.split()
print(result) # [] 空列表
# 连续分隔符处理
text = "a,,b,c,"
result = text.split(',')
print(result) # ['a', '', 'b', 'c', '']
2、print()
print(*变量名称):将列表中的每个元素单独打印出来,空格间隔
# 列表解包打印
fruits = ['apple', 'banana', 'orange']
print(*fruits) # apple banana orange
# 元组解包打印
numbers = (1, 2, 3, 4, 5)
print(*numbers) # 1 2 3 4 5
自定义分隔符sep
fruits = ['apple', 'banana', 'orange']
# 使用不同分隔符
print(*fruits, sep=', ') # apple, banana, orange
print(*fruits, sep=' | ') # apple | banana | orange
print(*fruits, sep='\n') # 每个元素单独一行
格式化输出
# 结合格式化字符串
numbers = [10, 20, 30]
print(*[f"数值: {num}" for num in numbers]) # 数值: 10 数值: 20 数值: 30
3、列表生成式
# 传统方式
old_list = [1, 2, 3, 4, 5]
new_list = []
for num in old_list:
new_list.append(num * 2)
# 列表生成式方式
new_list = [num * 2 for num in old_list]
print(new_list) # [2, 4, 6, 8, 10]
遍历旧列表,通过统一操作,快速生成新列表
不会改变遍历的列表,而是生成一个新列表
[表达式 for 循环变量 in 列表名称]
new_list=[int(i) for i in list]
# 字符串列表转整数列表
str_list = ['1', '2', '3', '4', '5']
int_list = [int(i) for i in str_list]
print(int_list) # [1, 2, 3, 4, 5]
# 整数列表转字符串列表
int_list = [1, 2, 3, 4, 5]
str_list = [str(i) for i in int_list]
print(str_list) # ['1', '2', '3', '4', '5']
带条件的列表生成式
# 只处理偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_squares = [num**2 for num in numbers if num % 2 == 0]
print(even_squares) # [4, 16, 36, 64, 100]
# 多条件筛选
numbers = range(1, 21)
result = [num for num in numbers if num % 2 == 0 and num % 3 == 0]
print(result) # [6, 12, 18]
嵌套循环
# 生成坐标对
rows = [1, 2, 3]
cols = ['A', 'B', 'C']
coordinates = [(row, col) for row in rows for col in cols]
print(coordinates) # [(1, 'A'), (1, 'B'), (1, 'C'), (2, 'A'), ...]
4、float()
将其他数据类型转换成浮点数类型
# 整数转浮点数
print(float(12)) # 12.0
print(float(-5)) # -5.0
# 字符串转浮点数
print(float('2.3')) # 2.3
print(float('5')) # 5.0
print(float('-3.14')) # -3.14
对比 int()
print(int(12)) >>>12
print(int('2.3')) >>>程序报错,不能填浮点类型
print(int('5')) >>> 5
科学计数法
print(float('1.23e4')) # 12300.0
print(float('1.23e-2')) # 0.0123
更多推荐

所有评论(0)