python学习-列表3(列表方法)

# 通过“对象.方法"调用

# index(要查找的元素,起始位置,结束位置)方法:用于获取指定元素在列表中第一次出现时索引,如果指定元素不存在,则抛出异常
stus = ['lili', 'tom', 'wuli', 'yuyo', 'lucky']
print(stus.index('lucky'))  # 输出4
print(stus.index('yuyo', 2, 4))  # 输出3

# count()方法:用于统计指定元素在列表中出现的次数
stus = ['lili', 'tom', 'wuli', 'tom', 'lucky', 'june']
print(stus.count('zhangshan'))  # 输出0
print(stus.count('tom'))  # 输出2

# append()方法:向列表的最后添加一个元素
stus = ['lili', 'tom', 'wuli', 'tom', 'lucky', 'june']
stus.append('susa')
print(stus)  # 输出['lili', 'tom', 'wuli', 'tom', 'lucky', 'june', 'susa']

# insert(插入的位置,插入的元素)方法:向列表的指定位置插入一个元素
arr = [1, 2, 3, 4, 7, 8]
arr.insert(4, 5)  # 在第4个位置插入数字5
print(arr)  # 输出:[1, 2, 3, 4, 5, 7, 8]

# extend()方法:使用新的序列来扩展当前序列
stus = ['lili', 'tom', 'wuli', 'tom']
stus.extend(['张三', '李四'])
print(stus)  # 输出:['lili', 'tom', 'wuli', 'tom', '张三', '李四']

# clear()方法:清空序列
stus = ['lili', 'tom', 'wuli', 'tom']
stus.clear()
print(stus)  # 输出:[]

# pop()方法:根据索引删除并返回被删除的元素
stus = ['lili', 'tom', 'wuli', 'tom']
stus.pop(2)  # 删除索引为2的元素
print(stus)  # 输出:['lili', 'tom', 'tom']
stus.pop()  # 删除最后一个元素
print(stus)  # 输出:['lili', 'tom']

# remove()方法:删除指定值的元素,如果相同元素有多个,则只会删除第一个
stus = ['lili', 'tom', 'wuli', 'tom']
stus.remove('tom')
print(stus)  # 输出: ['lili', 'wuli', 'tom']

# revese()方法:反转列表
stus = ['lili', 'tom1', 'wuli', 'tom2']
stus.reverse()
print(stus)  # 输出:['tom2', 'wuli', 'tom1', 'lili']

# sort()方法:对列表元素进行排序,默认是升序排列,如果需要降序排列,需要传递一个reverse=True作为参数
arr = list('derkgjdfshgdshe')
arr.sort()
print(arr)  # 输出:['d', 'd', 'd', 'e', 'e', 'f', 'g', 'g', 'h', 'h', 'j', 'k', 'r', 's', 's']
arr.sort(reverse=True)
print(arr)  # 输出:['s', 's', 'r', 'k', 'j', 'h', 'h', 'g', 'g', 'f', 'e', 'e', 'd', 'd', 'd']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值