ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

3.列表

2021-10-24 21:34:21  阅读:198  来源: 互联网

标签:motorcycles 示例 cars 列表 print ###


第3节列表 #3.1列表的特性:有序,元素可以重复,可以存放多种类型 #注:索引是从0开始(开头起始) #   也可以从-1开始(结尾起始) #3.2修改、添加和删除元素 ##修改 ###示例: motorcycles=['honda','yamaha','suzuki'] print(motorcycles)
motorcycles[0]='ducati'  #将motorcycles中索引为0的honda修改为ducati print(motorcycles)
##附加 ###示例: motorcycles=['honda','yamaha','suzuki'] print(motorcycles)
motorcycles.append('ducati') #在列表末尾添加元素ducati print(motorcycles) ###也可用创建一个空列表,再一个个添加元素 name=[] name.append('Job') name.append('Bob') name.append('Steven') print(name)
##插入 ###示例: motorcycles=['honda','yamaha','suzuki'] print(motorcycles) motorcycles.insert(0,'ducati')   #在索引为0的元素前面添加元素ducati print(motorcycles)
##删除 ###根据索引删除元素但不可使用它 ####示例: motorcycles=['honda','yamaha','suzuki'] print(motorcycles) del motorcycles[1]  #删除索引为1的元素 print(motorcycles)
###删除列表末尾的元素并使用它(弹出元素) ####示例: popped_motorcycle=motorcycles.pop()   #定义被方法pop()删除的元素 print(motorcycles)  #打印原列表 print(popped_motorcycle)  #打印被删除的元素
###根据值删除元素并使用它的值(弹出元素) ####示例: motorcycles=['honda','yamaha','suzuki','ducati'] print(motorcycles) motorcycles.remove('ducati') print(motorcycles)
motorcycles=['honda','yamaha','suzuki','ducati'] too_exepensive='ducati'   #定义要删除的元素 motorcycles.remove(too_exepensive)   #删除被定义的元素 print(motorcycles)   #打印原列表 print(f"\nA{too_exepensive.title()} is too expensive for me") #将被删除的元素插入句子中并换行打印这个句子
#3.3组织列表(在并非所有值都是小写时,按字母排序要复杂一点) ##使用sort()方法对列表永久排序(按字母顺序排序) ###示例: cars=['bmw','audi','toyota','subaru'] cars.sort() print(cars)
##按与字母顺序相反的顺序排列元素(向sort()方法传递函数reverse=True) ###示例: cars=['bmw','audi','toyota','subaru'] cars.sort(reverse=True) print(cars)
##使用函数sorted()对列表临时排序(字母顺序) ###示例: cars=['bmw','audi','toyota','subaru'] print("Here is the original list:") print(cars)
print("\nHere is the sorted list:") print(cars)
print("\nHere is the original list again:") print(cars)
##倒着打印列表 ###示例: cars=['bmw','audi','toyota','subaru'] print(cars) cars.reverse() print(cars)
##确定列表的长度 ###示例: cars=['bmw','audi','toyota','subaru'] len(cars)       #列表长度用列表元素的个数表示 print(len(cars))

标签:motorcycles,示例,cars,列表,print,###
来源: https://www.cnblogs.com/caujie/p/15455757.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有