python编程从入门到实践--第3章 列表简介
一。列表及使用
列表相当于其它语言的可变数组,使用下标法引用,特殊之处可以用负数的下标引用尾部元素,-1最后一个元素,-2倒数第二个元素,依此类推。
bicycles = ['trek', 'cannondale', 'redline', 'specialized'] print(bicycles) # 打印整个数列表 print(bicycles[0]) # 访问元素 print(bicycles[-1].title()) # 访问最后一个元素 print(bicycles[-2].title()) # 访问倒数第二个元素
二。列表的修改、添加和删除元素
# 修改元素值 motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) motorcycles[0] = 'ducati' motorcycles.append('honda') print(motorcycles) # 尾部添加元素--相当于入栈 names = [] names.append('Qingfeng Qian') names.append('Bin Wang') names.append('Cang Chen') print(names) #指定位置插入元素 names.insert(0, 'Kuo Zhang') print(names) names.insert(2, 'Mao Mao') print(names) #删除指定位置元素 del names[0] print(names) #弹出元素--删除末尾元素,相当于出栈 poped_name = names.pop() print(names) print(poped_name) # 假定列表是以时间为序的 last_owned = motorcycles.pop() print(f"The last motorcycle I owned waws a {last_owned.title()}") # 弹出特定位置元素 first_owned = motorcycles.pop(0) print(f"The first motorcycle I owned waw a {first_owned.title()}") # 按值删除元素 too_expensive = 'suzuki' motorcycles.remove(too_expensive) print(motorcycles) print(f'\nA {too_expensive.title()} is too expensive for me.')
三。排序、反转与长度
cars = ['bmw', 'audi', 'toyota', 'subaru'] # # 永久性排序 # cars.sort() # 默认升序 # print(cars) # cars.sort(reverse=True) # print(cars) #降序 # 临时排序 print("Here is the original list:") print(cars) print("\nHere is the sorted list:") print(sorted(cars)) print("\nHere is the original list agin:") print(cars) # 反转 print("\nHere is the reverse list:") cars.reverse() print(cars) # 长度 print(len(cars))
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通