第3章 列表操作

3.1 列表定义
列表是由一系列按照特定顺序排列的元素组成。可以包含字母表,数字0-9或所有家庭成员姓名的列表;也可以将任何东西加入到列表中
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)

3.2 访问列表元素

print(bicycles[0])
print(bicycles[0].title())
print(bicycles[-1])
3.3 修改列表元素
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles[0] = 'ducati'
print(motorcycles)
3.4 在列表末尾添加元素
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.append('ducati')
print(motorcycles)
3.5 在列表中插入元素
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
3.6 使用del语句删除元素
motorcycles = ['honda', 'yamaha', 'suzuki']
del motorcycles[0]
print(motorcycles)
3.7 使用方法pop() 删除元素
方法pop() 可删除列表末尾的元素
motorcycles = ['honda', 'yamaha', 'suzuki']
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
3.8 使用pop()弹出列表中任何位置处的元素
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
使用del 语句还是pop() 方法的判断标准:
如果你要从列表中删除一个元素,且不再以任何方式使用它,就使用del 语句;如果你要在删除元素后还能继续使用它,就使用方法pop() 。
3.9 根据值删除元素
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
motorcycles.remove('ducati')
print(motorcycles)
3.10 使用方法sort() 对列表进行永久性排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
3.11 使用函数sorted() 对列表进行临时排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(sorted(cars))
3.12 使用方法reverse()倒着打印列表
reverse() 不是指按与字母顺序相反的顺序排列列表元素,而只是反转列表元素的排列顺序
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)
3.13 使用函数len() 可快速获悉列表的长度
3.14 遍历整个列表
使用for 循环
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
3.15 创建数值列表
1)使用函数range()
for value in range(1,6):
print(value)
2)使用range()创建数字列表
numbers = list(range(1,6))
print(numbers)
3.16 列表解析
for 语句末尾没有冒号
squares = [value**2 for value in range(1,11)]
print(squares)
3.17 切片
用于处理列表的部分元素
players = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[0:3])
print(players[1:4])
print(players[:4])
print(players[2:])
print(players[-3:])
3.18 复制列表
方法是同时省略起始索引和终止索引([:] )。
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. 访问列表元素 索引从0开始而不是1 bicycles = ['trek','cannondale','red...
    LorryZ阅读 1,261评论 0 0
  • 视频看无聊了,也不想再看廖雪峰的教程了。 现在开始记录《Python编程:从入门到实践》的笔记和进度。 字符串: ...
    开发猛男阅读 799评论 0 0
  • 一、快捷键 ctr+b 执行ctr+/ 单行注释ctr+c ...
    o_8319阅读 11,102评论 2 16
  • 1、去python官网下载安装python即可在终端窗口运行程序 2、下载文本编辑器 Sublime text3 ...
    梦vctor阅读 3,122评论 0 0
  • 年一度的生日又到了,我很兴奋。 去年我十岁生日办的很热闹,来来去去有将近二十人。结果我妈说太烦了,况且现...
    佛语空灵阅读 1,729评论 0 0