python编程从入门到实践2——列表
admin
2024-03-17 08:27:18
0

目录

  • 2. 列表介绍
    • 2.1 列表是什么
      • 2.1.1 访问列表元素
      • 2.1.2 索引从0而不是1开始
    • 2.2 修改、添加和删除元素
      • 2.2.1 修改列表元素
      • 2.2.2 在列表中添加元素
      • 2.2.3 从列表中删除元素
    • 2.3 组织列表
      • 2.3.1 使用方法sort() 对列表进行 永久性排序
      • 2.3.2 使用函数sorted() 对列表进行 临时排序
      • 2.3.3 倒着打印列表
      • 2.3.4 确定列表的长度
  • 3. 操作列表
    • 3.1 遍历整个列表
    • 3.2 创建数值列表
      • 3.2.1 使用函数range()
      • 3.2.2 使用range() 创建数字列表
      • 3.2.3 对数字列表执行简单的统计计算
      • 3.2.4 列表解析
    • 3.3 使用列表的一部分
      • 3.3.1 切片
      • 3.3.2 复制列表

2. 列表介绍

2.1 列表是什么

用方括号([] )来表示列表,并用逗号来分隔其中的元素。列表 由一系列按特定顺序排列的元素组成。你可以创建包含字母表中所有字母、数字。

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)# ['trek', 'cannondale', 'redline', 'specialized']

2.1.1 访问列表元素

只需将该元素的位置索引告诉Python即可。

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0])# trek# 可使用方法title() 让元素'trek' 的格式更整洁:
print(bicycles[0].title())# Trek

2.1.2 索引从0而不是1开始

第一个列表元素的索引为0

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[1])
print(bicycles[3])# cannondale
# specialized

将索引指定为 -1 ,可让Python返回最后一个列表元素

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[-1])# specialized

2.2 修改、添加和删除元素

2.2.1 修改列表元素

motorcycles = ['honda', 'yamaha', 'suzuki'] 
print(motorcycles)
# ['honda', 'yamaha', 'suzuki'] motorcycles[0] = 'ducati' 
print(motorcycles)
# ['ducati', 'yamaha', 'suzuki'] 

2.2.2 在列表中添加元素

  1. 在列表末尾添加元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
# ['honda', 'yamaha', 'suzuki']motorcycles.append('ducati') 
print(motorcycles)# ['honda', 'yamaha', 'suzuki', 'ducati']motorcycles2 = []motorcycles2.append('honda')
motorcycles2.append('yamaha')
motorcycles2.append('suzuki')print(motorcycles2)
# ['honda', 'yamaha', 'suzuki', 'ducati']
  1. 在列表中插入元素
motorcycles = ['honda', 'yamaha', 'suzuki']motorcycles.insert(0, 'ducati') ❶
print(motorcycles)
# ['ducati', 'honda', 'yamaha', 'suzuki']

2.2.3 从列表中删除元素

  1. 使用del 语句删除元素,删除后,你就无法再访问它了。
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
# ['honda', 'yamaha', 'suzuki']del motorcycles[0] 
print(motorcycles)
# ['yamaha', 'suzuki']

del 可删除任何位置处的列表元素,条件是知道其索引。

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)del motorcycles[1]
print(motorcycles)# ['honda', 'yamaha', 'suzuki']
# ['honda', 'suzuki']
  1. 使用方法pop() 删除末尾元素

方法pop() 可删除列表末尾的元素,并让你能够接着使用它。术语弹出 (pop)源自这样的类比:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素。

motorcycles = ['honda', 'yamaha', 'suzuki'] 
print(motorcycles)popped_motorcycle = motorcycles.pop() 
print(motorcycles) 
print(popped_motorcycle) # ['honda', 'yamaha', 'suzuki']
# ['honda', 'yamaha']
# suzuki
motorcycles = ['honda', 'yamaha', 'suzuki']last_owned = motorcycles.pop()
print("The last motorcycle I owned was a " + last_owned.title() + ".")# The last motorcycle I owned was a Suzuki.
  1. 弹出列表中任何位置处的元素
    pop()+索引
motorcycles = ['honda', 'yamaha', 'suzuki']first_owned = motorcycles.pop(0) ❶
print('The first motorcycle I owned was a ' + first_owned.title() + '.')# The first motorcycle I owned was a Honda.
  1. 根据值删除元素

方法remove()

motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)motorcycles.remove('ducati') 
print(motorcycles)# ['honda', 'yamaha', 'suzuki', 'ducati']
# ['honda', 'yamaha', 'suzuki']
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] ❶
print(motorcycles)too_expensive = 'ducati' ❷
motorcycles.remove(too_expensive) ❸
print(motorcycles)
print("\nA " + too_expensive.title() + " is too expensive for me.") # \n 回车# ['honda', 'yamaha', 'suzuki', 'ducati']
# ['honda', 'yamaha', 'suzuki']# A Ducati is too expensive for me.

2.3 组织列表

2.3.1 使用方法sort() 对列表进行 永久性排序

sort(),永久性地修改了列表元素的排列顺序。

cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort() ❶
print(cars)# ['audi', 'bmw', 'subaru', 'toyota']

相反的顺序,向sort() 方法传递参数reverse=True

cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)# ['toyota', 'subaru', 'bmw', 'audi']

2.3.2 使用函数sorted() 对列表进行 临时排序

调用函数sorted() 后,列表元素的排列顺序并没有变。如果你要按与字母顺序相反的顺序显示列表,也可向函数sorted() 传递参数reverse=True

cars = ['bmw', 'audi', 'toyota', 'subaru']print("Here is the original list:") ❶
print(cars)print("\nHere is the sorted list:") ❷
print(sorted(cars))print("\nHere is the original list again:") ❸
print(cars)

output:

Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']  # 临时排序Here is the original list again: ❹
['bmw', 'audi', 'toyota', 'subaru']  # 原始顺序

2.3.3 倒着打印列表

reverse() ,永久性地修改列表元素的排列顺序,但可随时恢复到原来的排列顺序,为此只需对列表再次调用reverse() 即可。

cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)cars.reverse()
print(cars)# ['bmw', 'audi', 'toyota', 'subaru']
# ['subaru', 'toyota', 'audi', 'bmw']

2.3.4 确定列表的长度

len()

>>> cars = ['bmw', 'audi', 'toyota', 'subaru']
>>> len(cars)
4

3. 操作列表

3.1 遍历整个列表

for循环

magicians = ['alice', 'david', 'carolina'] ❶
for magician in magicians: ❷print(magician) ❸alice
david
carolina

3.2 创建数值列表

3.2.1 使用函数range()

for value in range(1,5):print(value)
# 输出
1
2
3
4for value in range(1,6):print(value)
1
2
3
4
5

3.2.2 使用range() 创建数字列表

numbers = list(range(1,6))
print(numbers)# [1, 2, 3, 4, 5]even_numbers = list(range(2,11,2))
print(even_numbers)# [2, 4, 6, 8, 10]

3.2.3 对数字列表执行简单的统计计算

>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> min(digits)
0>>> max(digits)
9>>> sum(digits)
45

3.2.4 列表解析

列表解析 将for 循环和创建新元素的代码合并成一行,并自动附加新元素。

squares = [value**2 for value in range(1,11)]
print(squares)# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

3.3 使用列表的一部分

3.3.1 切片

players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3]) ❶
['charles', 'martina', 'michael']players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1:4])
['martina', 'michael', 'florence']players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4])
['charles', 'martina', 'michael', 'florence']
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:])
['michael', 'florence', 'eli']
print(players[-3: -1])
['michael', 'florence']

3.3.2 复制列表

要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:] )。这让Python创建一个始于第一个元素,终止于最后一个元素的切片,即复制整个列表。

my_foods = ['pizza', 'falafel', 'carrot cake'] ❶
friend_foods = my_foods[:] ❷print("My favorite foods are:")
print(my_foods)print("\nMy friend's favorite foods are:")
print(friend_foods)

输出:

My favorite foods are:
['pizza', 'falafel', 'carrot cake']My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake']

另外

my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:] ❶my_foods.append('cannoli') ❷
friend_foods.append('ice cream') ❸print("My favorite foods are:")
print(my_foods)print("\nMy friend's favorite foods are:")
print(friend_foods)# My favorite foods are:
# ['pizza', 'falafel', 'carrot cake', 'cannoli'] ❹# My friend's favorite foods are:
# ['pizza', 'falafel', 'carrot cake', 'ice cream'] ❺

错误方法:

my_foods = ['pizza', 'falafel', 'carrot cake']#这行不通
friend_foods = my_foods ❶my_foods.append('cannoli')
friend_foods.append('ice cream')print("My favorite foods are:")
print(my_foods)print("\nMy friend's favorite foods are:")
print(friend_foods)

输出:

My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']

相关内容

热门资讯

AI硬件方向局部活跃,科创创业... 节后归来第一周,HBM、电路板、覆铜板等AI硬件方向表现活跃。指数层面,中证科创创业人工智能指数上涨...
刘建军功成身退,芦苇接棒的邮储... 文 / 董轩 来源 / 节点财经 新年伊始,银行业的高层人事变动悄然提速。有人履新赴任,执掌帅印...
原创 2... 马年刚开工,地产圈就被一场土拍炸醒了。 2月25日,广州迎来农历新年后首场重磅土拍——珠江新城马场地...
苏州科达大宗交易溢价成交107... 苏州科达02月27日大宗交易平台共发生1笔成交,合计成交量107.00万股,成交金额1136.34万...
中信证券:AI冲击被夸大,维持... 近日,全球保险类股票集体陷入回调模式,欧美多家保险股2月下跌,尤其是一些老牌保险经纪巨头股价跌幅较大...
城商行“优等生”换帅,准80后... 城商行阵营的“优等生”宁波银行再现系列人事变动。2月26日,宁波银行发布公告称,该行在当天召开的第九...
摩根大通:市场对AI担忧过度 ... 【摩根大通:市场对AI担忧过度 现在是优质软件公司最佳抄底时机】财联社2月27日电,随着“人工智能(...
汇嘉时代精准承接消费政策红利 ... 马年新春消费热潮持续涌动,新疆零售龙头企业汇嘉时代(603101.SH)交出亮眼成绩单。据不完全统计...
马年首个交易周A股主要指数集体... 马年首个交易周,A股主要指数集体收涨,上证指数涨近2%逼近1月高点,全市场日均成交额有所放大。板块题...
抑郁儿子偏执易怒,不是叛逆期作... 阿文是一名高三年级的男生,他一脸的愁容,“刘老师,我近来感觉压力很大,上次区运动会我长跑拿了前三名,...
库克官宣苹果“发布大周”,iP... 【环球网科技综合报道】2月27日消息,据外媒MacRumors报道,苹果CEO蒂姆·库克日前发布预告...
中美大反转,中国AI调用量首超... 当地时间2月26日,刚刚发布财报的英伟达股价大跌5.5%,市值蒸发近2600亿美元,而2月27日A股...
“电诈清零”最后期限仅剩两月,... 当地时间25日,柬埔寨首相洪玛奈在比利时罕见接受采访。在谈及该国电诈相关事宜时,他直言,这种“黑色经...
五年了,公司还没申报IPO:董... 来源:IPO上市号 有个读者留言说,他在一家拟IPO企业已经干了五年董秘,从35岁干到现在40岁,头...
民德电子10亿定增:产能爬坡未... 2月26日晚,民德电子(300656.SZ)抛出不超过10亿元定增预案,拟将7亿元投向控股子公司广芯...
调查!美诚月饼50万元罚单背后... 华夏时报记者 胡梦然 见习记者 黄海婷 深圳摄影报道 近日,因存在虚假宣传违法行为,去年深陷舆论风...
终结四连降,金龙鱼2025年净... 图片来源:视觉中国 蓝鲸新闻2月27日讯(记者 代紫庭)2月26日晚间,粮油行业龙头金龙鱼(3009...
焦点复盘沪指周线、月线均创阶段... 财联社2月27日讯,今日75股涨停,16股炸板,封板率为82%,豫能控股7连板,金正大、章源钨业7天...
原创 父... 在大多数人的想象中,首富的女儿应该过着衣来伸手,饭来张口的生活…… 她们从小就含着金汤匙出生,长大后...
陷入致命僵持,今晚黄金一锤定音... 隔夜,现货黄金维持窄幅震荡,收盘微涨0.4%至5183.88美元,盘中一度跌至5130美元附近但很快...