Python中列表的常用方法

本文介绍了Python编程中常用的列表操作,包括append、insert、count、remove、reverse、sort、clear和copy等方法,详细解释了每个方法的功能和用法,并通过示例展示了它们在实际编程中的应用。掌握这些基本操作对于提升Python编程能力至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# coding:utf-8

# append方法:在列表中添加一项
from typing import AsyncGenerator, Counter


info = ["chinese","math","enghish"]
info.append("art")
print(info)   # 输出:['chinese', 'math', 'enghish', 'art']

# insert方法:指定的索引位置处添加一项
name = ["xiaohong","xiaoming","xiaolan"]
name.insert(1,"yuyun")
print(name)  # ['xiaohong', 'yuyun', 'xiaoming', 'xiaolan']

# count:统计字符串在列表中出现的次数
fruit = ["apple","apple","apple","banana","orange"]
print(fruit.count("apple"))   # 输出 3

# remove:移除列表中的某一项
fruit = ["apple","apple","apple","banana","orange"]
fruit.remove("apple")
print(fruit)  # 输出: ['apple', 'apple', 'banana', 'orange']

# reverse 将列表中的字符串逆序
num = [1,2,3,4,5,6,7,8]
num.reverse()
print(num) # 输出:[8, 7, 6, 5, 4, 3, 2, 1]

# sort:将字符串按照一定的顺序排列
age = [11,13,14,15,16]
age.sort(reverse=False)   #升序 列表中的元素必须是同类型的
print(age)   # [11, 13, 14, 15, 16]
new_age = [88,78,89,76]
new_age.sort(reverse=True)  # 降序  列表中的元素必须是同类型的
print(new_age)   # [89, 88, 78, 76]

# clear 清空列表
car = ["aodi","bmw","benchi"]
car.clear()
print(car)  #[]

# copy
a = ["bai","red","yellow","blue"]
b = a.copy()
print(b)   # ['bai', 'red', 'yellow', 'blue']
b.append(1)
print(a) #'bai', 'red', 'yellow', 'blue']
print(b) #['bai', 'red', 'yellow', 'blue', 1]
print(id(a))# 31968648
print(id(b)) #31968616

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值