博客
关于我
Python:公共操作-公共方法
阅读量:798 次
发布时间:2023-04-16

本文共 1568 字,大约阅读时间需要 5 分钟。

公共方法

1. len() 函数

len() 用于计算容器中元素的个数。它适用于字符串、列表、元组和字典等数据容器。

示例

  • 字符串 str1 = 'abcd'
    print(len(str1))  # 输出: 4
  • 列表 list1 = ['孙权', 18, '男']
    print(len(list1))  # 输出: 3
  • 元组 tuple1 = (10, 20, 30)
    print(len(tuple1))  # 输出: 3
  • 字典 dict1 = {'name': '孙权', 'age': 18, 'sex': '男'}
    print(len(dict1))  # 输出: 3

2. del 或 del() 函数

del 用于删除容器中的元素,支持通过索引、切片或键来删除。

示例

  • 字符串 str1 = 'abcd'
    del str1print(str1)  # 输出: 'abcd'(注意:删除操作不会改变字符串内容)
  • 列表 list1 = ['孙权', 18, '男']
    del list1[1]print(list1)  # 输出: ['孙权', '男']
  • 字典 dict1 = {'name': '孙权', 'age': 18, 'sex': '男'}
    del dict1['age']print(dict1)  # 输出: {'name': '孙权', 'sex': '男'}

3. max 和 min 函数

max() 和 min() 用于查询容器中最大或最小值,适用于字符串、列表、元组等数据类型。

示例

  • 字符串 asiicastr1 = 'abcdefg'
    print(max(str1))  # 输出: 'g'print(min(str1))  # 输出: 'a'
  • 列表 list1 = [10, 20, 30, 40]
    print(max(list1))  # 输出: 40print(min(list1))  # 输出: 10
  • 元组 tuple1 = (10, 20, 30, 40)
    print(max(tuple1))  # 输出: 40print(min(tuple1))  # 输出: 10

4. range() 函数

range() 用于生成一系列数据,支持指定起始、结束和步长。

示例

  • 生成 1-10 数据
    for i in range(1, 10, 1):    print(i)  # 输出: 1 2 3 4 5 6 7 8 9
  • 生成 1-10 的奇数
    for i in range(1, 10, 2):    print(i)  # 输出: 1 3 5 7 9
  • 生成 0-9 数据
    for i in range(10):    print(i)  # 输出: 0 1 2 3 4 5 6 7 8 9

5. enumerate() 函数

enumerate() 将数据转换为键值对形式,常用于遍历列表、元组等容器。

示例

  • 字符串 str1 = 'abcdefg'
    for i in enumerate(str1):    print(i)  # 输出: (0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g')
  • 列表 list1 = ['孙权', '男', 18]
    for i in enumerate(list1):    print(i)  # 输出: (0, '孙权'), (1, '男'), (2, 18)
  • 元组 tuple1 = (10, 20, 30, 40)
    for i in enumerate(tuple1):    print(i)  # 输出: (1, 20), (2, 30), (3, 40)

转载地址:http://hkgfk.baihongyu.com/

你可能感兴趣的文章
mysql8 配置文件配置group 问题 sql语句group不能使用报错解决 mysql8.X版本的my.cnf配置文件 my.cnf文件 能够使用的my.cnf配置文件
查看>>
MySQL8.0.29启动报错Different lower_case_table_names settings for server (‘0‘) and data dictionary (‘1‘)
查看>>
MYSQL8.0以上忘记root密码
查看>>
Mysql8.0以上重置初始密码的方法
查看>>
mysql8.0新特性-自增变量的持久化
查看>>
Mysql8.0注意url变更写法
查看>>
Mysql8.0的特性
查看>>
MySQL8修改密码报错ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
查看>>
MySQL8修改密码的方法
查看>>
Mysql8在Centos上安装后忘记root密码如何重新设置
查看>>
Mysql8在Windows上离线安装时忘记root密码
查看>>
MySQL8找不到my.ini配置文件以及报sql_mode=only_full_group_by解决方案
查看>>
mysql8的安装与卸载
查看>>
MySQL8,体验不一样的安装方式!
查看>>
MySQL: Host '127.0.0.1' is not allowed to connect to this MySQL server
查看>>
Mysql: 对换(替换)两条记录的同一个字段值
查看>>
mysql:Can‘t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock‘解决方法
查看>>
MYSQL:基础——3N范式的表结构设计
查看>>
MYSQL:基础——触发器
查看>>
Mysql:连接报错“closing inbound before receiving peer‘s close_notify”
查看>>