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快讯,7月28日,银行间主要利率债午间走势分化,30年期国债“26超长特别国债04”收益率下...
2026海河国际消费论坛即将在... 2026海河国际消费论坛将于7月30日下午在天津启幕,目前各项筹备工作已全部就绪。本届论坛以“创新服...
原创 一... 前言 1942年的一天,一名身穿军装的年轻人,悄悄走到一位老妇人的面前。他脸上带着疲惫,眼神中却依然...
原创 曹... 八十岁的曹德旺,这几年在公开场合谈到房子这两个字,语气一次比一次冷。他早年那句"房子不过是钢筋水泥堆...
股息率近5.5%!港股红利低波... 7月28日,港股红利资产延续强势。截至13时48分,港股红利低波ETF招商(520550)涨0.46...
企业文件共享平台怎么选?主流方... 文件共享平台种类繁多,各有侧重。今天这篇文章,把2026年市面上主流的企业文件共享平台做个系统梳理,...
币圈院士:7.26以太坊(ET... 币圈院士:7.26以太坊(ETH)双周期指标暗藏方向,行情即将破位?最新行情分析参考 以太坊现价18...
老铺黄金发盈喜后股价跌16.2... 观点网讯:7月28日,老铺黄金股价裂口低开12.97%,最低见325.8港元,收盘报332港元,跌1...
苏泊尔上半年营收净利双降,法籍... 瑞财经 严明会 近日,苏泊尔(002032.SZ)披露2026年半年度业绩快报。 公告显示,公司上半...
IPO雷达|陕西瑞科回复二轮问... 深圳商报·读创客户端记者 梁佳彤 7月27日,据北交所官网,陕西瑞科新材料股份有限公司(下称“陕西瑞...
普京签令,俄军扩编 据新华社报道,俄罗斯总统普京27日签署命令, 决定组建几支军事建筑工程部队,并将俄武装力量编制总人数...
2027年德国杜塞尔多夫国际铸... 展会名称:2027年德国杜塞尔多夫国际铸造、冶金、热处理及铸件展览会GMTN 开始时间:2027-0...
郑州有了温通刮痧培训示范基地 本报讯(记者 杨振东 通讯员 张丹婧)温通刮痧是中医外治法里的一种,简单说就是在传统刮痧基础上,结合...
整箱茅台和单瓶茅台,回收行情为... 不少天津藏友存在疑惑:同样年份、同样品相的飞天茅台,整箱装和拆箱单瓶的回收报价存在差距,不清楚背后的...
北京五粮液收购需要遵循哪些通用... 北京五粮液收购的行业背景 近年来高端白酒的收藏与流通市场规模稳步扩张,北京作为国内重要的消费城市,五...
微软CEO重磅警告:只依赖一家... 来源:环球网 【环球网科技综合报道】7月28日消息,据外媒TechCrunch报道,微软CEO萨提亚...
策略师:金价夏季维持4000美... 汇通财经APP讯——今夏金价大概率在4000美元/盎司附近震荡筑底,市场等待美联储货币政策清晰指引。...
大众叙事下白酒行业周期如何拆解... 白酒行业的波动往往并非单纯由供需关系决定,而是 宏观经济预期与 渠道库存周期共振的结果。在大众认知中...
沈皓南:黄金低位大区间运行,短... 大家好,我是沈皓南,差不多有一个月没有更新黄金文章了,这段时间我去了美丽的新疆,自驾了独库公路,观赏...
原创 上... 2000年9月28日傍晚,济青高速临淄出口边一家小饭馆的木门被推开,六个山东汉子鱼贯而入。几个小时前...