Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python常见函数

作者:殘月殺手   发布日期:2025-05-31   浏览:116

# Python 常见函数示例

# 1. len() - 获取字符串、列表、元组等的长度
example_string = "Hello, world!"
print(f"字符串 '{example_string}' 的长度是: {len(example_string)}")

# 2. range() - 生成一个整数序列
for i in range(5):
    print(i, end=" ")  # 输出: 0 1 2 3 4

# 3. type() - 获取变量的数据类型
example_variable = 42
print(f"变量 example_variable 的类型是: {type(example_variable)}")

# 4. str(), int(), float() - 数据类型转换
number_str = "123"
number_int = int(number_str)
number_float = float(number_str)
print(f"字符串 '{number_str}' 转换为整数是: {number_int}, 转换为浮点数是: {number_float}")

# 5. list() - 将其他数据类型转换为列表
example_tuple = (1, 2, 3)
example_list = list(example_tuple)
print(f"元组 {example_tuple} 转换为列表是: {example_list}")

# 6. dict() - 创建字典或将其他数据类型转换为字典
example_dict = dict(name="Alice", age=30)
print(f"创建的字典是: {example_dict}")

# 7. sum() - 计算数值列表的总和
numbers = [1, 2, 3, 4, 5]
total_sum = sum(numbers)
print(f"列表 {numbers} 的总和是: {total_sum}")

# 8. sorted() - 对列表进行排序
unsorted_list = [3, 1, 4, 1, 5, 9]
sorted_list = sorted(unsorted_list)
print(f"未排序的列表 {unsorted_list} 排序后是: {sorted_list}")

# 9. max() 和 min() - 获取最大值和最小值
max_value = max(unsorted_list)
min_value = min(unsorted_list)
print(f"列表 {unsorted_list} 中的最大值是: {max_value}, 最小值是: {min_value}")

# 10. zip() - 将多个列表配对
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
paired_data = list(zip(names, ages))
print(f"名字和年龄配对后的结果是: {paired_data}")

解释说明:

  • len():用于获取对象(如字符串、列表、元组等)的长度。
  • range():用于生成一个整数序列,常用于循环中。
  • type():用于获取变量的数据类型。
  • str(), int(), float():用于在不同数据类型之间进行转换。
  • list():将其他数据类型(如元组)转换为列表。
  • dict():用于创建字典或将其他数据类型转换为字典。
  • sum():用于计算数值列表的总和。
  • sorted():用于对列表进行排序。
  • max()min():分别用于获取列表中的最大值和最小值。
  • zip():用于将多个列表配对,返回一个包含元组的迭代器。

上一篇:python零基础教学

下一篇:sql python

大家都在看

python时间格式

python ord和chr

python中的yield

python自定义异常

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站