序列
序列 有序。
字符串, 列表, 元组 都属于序列
下面主要针对列表与元组进行说明
列表(可变)
列表定义
列表由一些系列按特定顺序排列的元素组成。可以创建包含字母表中所有字母,数字0~9;也可以将任何东西加入列表中,其中的元素之间可以没有任何关系,也可以是不同数据类型。
[]构建,并用逗号来分隔其中的元素,里面的元素可以是不同类型(字符串,数字,布尔,列表(嵌套列表)等
(不同于Java,Java定义一个List后里面的类型是需要相同的)
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
message = "My first bicycle was a " + bicycles[0].title() + "."
print(message)
执行结果:
My first bicycle was a Trek.
-
访问列表元素
列表是有序集合,要访问列表任何元素,只需要根据该元素的位置或索引来访问即可。
指出列表的名称,再指出元素的索引,并将其放在方括号内。
当请求获取列表元素时, Python只返回该元素,而不包括方括号和引号bicycles = ['trek', 'cannondale', 'redline', 'specialized'] print(bicycles[0]) 执行结果: trek在Python中,第一个列表元素的索引为0, 这与列表操作的底层实现相关(//TODO)
要访问列表的任何元素,都可将其位置减1,并将结果作为索引bicycles = ['trek', 'cannondale', 'redline', 'specialized'] print(bicycles[1]) print(bicycles[3]) 执行结果: cannondale specializedPython为访问最后一个列表元素提供了一种特殊语法。通过将索引指定为-1,在不知道列表长度的情况下访问最后的元素。
这种约定也适用于其他负数索引,例如,索引-2 返回倒数第 二个列表元素,索引-3 返回倒数第三个列表元素,以此类推bicycles = ['trek', 'cannondale', 'redline', 'specialized'] print(bicycles[-1]) print(bicycles[-2]) 执行结果: specialized redline使用列表中各个值
可以像使用其他变量一样使用列表中和的各个值bicycles = ['trek', 'cannondale', 'redline', 'specialized'] print(bicycles) message = "My first bicycle was a " + bicycles[0].title() + "." print(message)示例:
names = ["Sunny", "Denny", "Jeecy", "Power", "Paul"] print(names[0]) print(names[1]) print(names[2]) print(names[3]) print(names[4]) # print(names[5]) # IndexError: list index out of range print('*' * 23) print(names[-1]) print(names[-2]) print(names[-3]) print(names[-4]) print(names[-5]) print('*' * 23) for name in names: print(name) 执行结果: Sunny Denny Jeecy Power Paul *********************** Paul Power Jeecy Denny Sunny *********************** Sunny Denny Jeecy Power Paulnames = ["Sunny", "Denny", "Jeecy", "Power", "Paul"] print("Hello %s, nice to meet you!" % names[0]) print("Hello %s, nice to meet you!" % names[1]) print("Hello %s, nice to meet you!" % names[2]) print("Hello %s, nice to meet you!" % names[3]) print("Hello %s, nice to meet you!" % names[4]) print('*' * 23) for name in names: print("Hello %s, nice to meet you!" % name) 执行结果: Hello Sunny, nice to meet you! Hello Denny, nice to meet you! Hello Jeecy, nice to meet you! Hello Power, nice to meet you! Hello Paul, nice to meet you! *********************** Hello Sunny, nice to meet you! Hello Denny, nice to meet you! Hello Jeecy, nice to meet you! Hello Power, nice to meet you! Hello Paul, nice to meet you!traffics = ["摩拜单车", "丰田凯美瑞", "小牛电动车"] print("我交通出行工具:{0}".format(traffics[0])) print("我交通出行工具:{0}".format(traffics[1])) print("我交通出行工具:{0}".format(traffics[2])) print('*' * 23) for traffic in traffics: print("我交通出行工具:{0}".format(traffic)) 执行结果: 我交通出行工具:摩拜单车 我交通出行工具:丰田凯美瑞 我交通出行工具:小牛电动车 *********************** 我交通出行工具:摩拜单车 我交通出行工具:丰田凯美瑞 我交通出行工具:小牛电动车 -
列表运算
+加拼接
*乘重复
-减不存在, TypeError: unsupported operand type(s) for -: 'list' and 'list'
2.1 + 加 拼接traffics1 = ["摩拜单车", "丰田凯美瑞", "小牛电动车"] traffics2 = ["美团单车", "青桔单车", "哈罗单车"] traffics = traffics1 + traffics2 print(traffics) 执行结果: ['摩拜单车', '丰田凯美瑞', '小牛电动车', '美团单车', '青桔单车', '哈罗单车']2.2 * 乘 重复
traffics = ["摩拜单车", "丰田凯美瑞", "小牛电动车"] print(traffics * 3) 执行结果: ['摩拜单车', '丰田凯美瑞', '小牛电动车', '摩拜单车', '丰田凯美瑞', '小牛电动车', '摩拜单车', '丰田凯美瑞', '小牛电动车'] -
操作列表元素(修改、添加和删除元素)
3.1修改- 直接通过索引访问修改
motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) motorcycles[0] = 'ducati' print(motorcycles) 执行结果: ['honda', 'yamaha', 'suzuki'] ['ducati', 'yamaha', 'suzuki']3.2 添加:
- 通过append()方法,在列表末尾添加元素
# 在列表末尾添加元素 motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) motorcycles.append('ducati') print(motorcycles) 执行结果: ['honda', 'yamaha', 'suzuki'] ['honda', 'yamaha', 'suzuki', 'ducati'] motorcycles = [] motorcycles.append('honda') motorcycles.append('yamaha') motorcycles.append('suzuki') print(motorcycles) 执行结果: ['honda', 'yamaha', 'suzuki']- 通过insert()在列表任何位置添加元素,需要指定新元素的索引与值
在列表指定位置x添加元素,原来x位置的元素以及后面的元素整体向后移动
# 在这个示例中, 值'ducati' 被插入到了列表开头; # 方法insert() 在索引0处添加空间,并将值'ducati'存储到这个地方。 # 这种操作将列表中既有的每个元素都右移一个位置: motorcycles = ['honda', 'yamaha', 'suzuki'] motorcycles.insert(0, 'ducati') print(motorcycles) 执行结果: ['ducati', 'honda', 'yamaha', 'suzuki']3.3 删除:
- 使用del语句删除元素
使用del 可删除任何位置处的列表元素, 条件是知道其索引。
使用del语句将值从列表中删除后,就无法再访问到了
删除指定索引的元素,后面的元素整体向前移动
motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) del motorcycles[0] print(motorcycles) 执行结果: ['yamaha', 'suzuki'] motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) del motorcycles[1] print(motorcycles) 执行结果: ['honda', 'yamaha', 'suzuki'] ['honda', 'suzuki']- 使用方法pop() 删除元素
方法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. 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.- remove()根据值删除
不知道要从列表中删除的值所处的位置。只知道要删除的元素的值,可以使用remove()。
根据值删除对应元素,后面的元素整体向前移动。
使用remove() 从列表中删除元素时, 也可接着使用它的值。
方法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.") 执行结果: ['honda', 'yamaha', 'suzuki', 'ducati'] ['honda', 'yamaha', 'suzuki'] A Ducati is too expensive for me.删除方式总结:
如果你要从列表中删除一个元素, 且不再以任何方式使用它, 就使用del 语句; 如果你要在删除元素后还能继续使用它, 就使用方法pop() 。
remove()返回的是None
示例:invitees = ["Denny", "Jeecy", "Power", "Paul", "Andy"] for invitee in invitees: print("Hello %s, invite you to a dinner party" % invitee) uattendname = "Power" print("%s, unable to attend" % uattendname) invitees.remove(uattendname) invitees.append("AB") for invitee in invitees: print("Hello %s, invite you to a dinner party" % invitee) print("I find a big table") invitees.insert(0, "Sunny") import math i = math.floor(len(invitee) / 2) + 1 invitees.insert(i, "CD") invitees.append("EF") for invitee in invitees: print("Hello %s, invite you to a dinner party" % invitee) print("Oh, My god, Table cannot be delivered in time, so Only Two invitees could come this party") while len(invitees) > 2: delinvitee = invitees.pop() print("I'm sorry %s, I Can't invite you to this party for some reason" % delinvitee) for invitee in invitees: print("Hello %s, still invite you to a dinner party" % invitee) for i in range(0, len(invitees)): del invitees[0] print(invitees) 执行结果: Hello Denny, invite you to a dinner party Hello Jeecy, invite you to a dinner party Hello Power, invite you to a dinner party Hello Paul, invite you to a dinner party Hello Andy, invite you to a dinner party Power, unable to attend Hello Denny, invite you to a dinner party Hello Jeecy, invite you to a dinner party Hello Paul, invite you to a dinner party Hello Andy, invite you to a dinner party Hello AB, invite you to a dinner party I find a big table Hello Sunny, invite you to a dinner party Hello Denny, invite you to a dinner party Hello CD, invite you to a dinner party Hello Jeecy, invite you to a dinner party Hello Paul, invite you to a dinner party Hello Andy, invite you to a dinner party Hello AB, invite you to a dinner party Hello EF, invite you to a dinner party Oh, My god, Table cannot be delivered in time, so Only Two invitees could come this party I'm sorry EF, I Can't invite you to this party for some reason I'm sorry AB, I Can't invite you to this party for some reason I'm sorry Andy, I Can't invite you to this party for some reason I'm sorry Paul, I Can't invite you to this party for some reason I'm sorry Jeecy, I Can't invite you to this party for some reason I'm sorry CD, I Can't invite you to this party for some reason Hello Sunny, still invite you to a dinner party Hello Denny, still invite you to a dinner party [] -
组织列表
创建的列表中, 元素的排列顺序常常是无法预测的。
经常需要以特定的顺序呈现信息。 有时候, 你希望保留列表元素最初的排列顺序, 而有时候又需要调整排列顺序。 Python提供了很多组织列表的方式, 可根据具体情况选用。
4.1 sort()对列表进行永久性排序
方法sort() 永久性地修改了列表元素的排列顺序, 再也无法恢复到原来的排列顺序:cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort() print(cars) 执行结果: ['audi', 'bmw', 'subaru', 'toyota'] cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort(reverse=True) print(cars) 执行结果: ['toyota', 'subaru', 'bmw', 'audi']4.2 sorted()对列表进行临时性排序
要保留列表元素原来的排列顺序, 同时以特定的顺序呈现它们, 可使用函数sorted() 。 函数sorted() 让你能够按特定顺序显示列表元素, 同时不影响它们在列表中的原始排列顺序。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 sorted list:") print(sorted(cars, reverse=True)) print("\nHere is the original list again:") print(cars) 执行结果: Here is the original list: ['bmw', 'audi', 'toyota', 'subaru'] Here is the sorted list: ['audi', 'bmw', 'subaru', 'toyota'] Here is the sorted list: ['toyota', 'subaru', 'bmw', 'audi'] Here is the original list again: ['bmw', 'audi', 'toyota', 'subaru']在并非所有的值都是小写时, 按字母顺序排列列表要复杂些,到底起逻辑是什么//TODO
4.3 列表倒序
要反转列表元素的排列顺序, 可使用方法reverse() ,将永远改变列表的顺序,但其实是可逆操作,再次调用reverse()即可恢复cars = ['bmw', 'audi', 'toyota', 'subaru'] print(cars) cars.reverse() print(cars) cars.reverse() print(cars) 执行结果: ['bmw', 'audi', 'toyota', 'subaru'] ['subaru', 'toyota', 'audi', 'bmw'] ['bmw', 'audi', 'toyota', 'subaru']4.4 确定列表长度
使用函数len() 可快速获悉列表的长度cars = ['bmw', 'audi', 'toyota', 'subaru'] print(len(cars)) 执行结果: 4示列:
destination = ["拉萨", "九寨沟", "长白山", "西双版纳", "重庆", "香港", "澳门", "马尔代夫", "塞班岛"] print(destination) print(sorted(destination)) print(destination) print(sorted(destination, reverse=True)) print(destination) destination.reverse() print(destination) destination.reverse() print(destination) destination.sort() print(destination) destination.sort(reverse=True) print(destination) 执行结果: ['拉萨', '九寨沟', '长白山', '西双版纳', '重庆', '香港', '澳门', '马尔代夫', '塞班岛'] ['九寨沟', '塞班岛', '拉萨', '澳门', '西双版纳', '重庆', '长白山', '香港', '马尔代夫'] ['拉萨', '九寨沟', '长白山', '西双版纳', '重庆', '香港', '澳门', '马尔代夫', '塞班岛'] ['马尔代夫', '香港', '长白山', '重庆', '西双版纳', '澳门', '拉萨', '塞班岛', '九寨沟'] ['拉萨', '九寨沟', '长白山', '西双版纳', '重庆', '香港', '澳门', '马尔代夫', '塞班岛'] ['塞班岛', '马尔代夫', '澳门', '香港', '重庆', '西双版纳', '长白山', '九寨沟', '拉萨'] ['拉萨', '九寨沟', '长白山', '西双版纳', '重庆', '香港', '澳门', '马尔代夫', '塞班岛'] ['九寨沟', '塞班岛', '拉萨', '澳门', '西双版纳', '重庆', '长白山', '香港', '马尔代夫'] ['马尔代夫', '香港', '长白山', '重庆', '西双版纳', '澳门', '拉萨', '塞班岛', '九寨沟'] invitees = ["Denny", "Jeecy", "Power", "Paul", "Andy"] for invitee in invitees: print("Hello %s, invite you to a dinner party" % invitee) uattendname = "Power" print("%s, unable to attend" % uattendname) invitees.remove(uattendname) invitees.append("Sunny") for invitee in invitees: print("Hello %s, invite you to a dinner party" % invitee) print('invitee Num:%d' % len(invitees)) 执行结果: Hello Denny, invite you to a dinner party Hello Jeecy, invite you to a dinner party Hello Power, invite you to a dinner party Hello Paul, invite you to a dinner party Hello Andy, invite you to a dinner party Power, unable to attend Hello Denny, invite you to a dinner party Hello Jeecy, invite you to a dinner party Hello Paul, invite you to a dinner party Hello Andy, invite you to a dinner party Hello Sunny, invite you to a dinner party invitee Num:5 roles = ["乔峰", "段誉", "虚竹", "杨过", "小龙女", "郭靖", "黄蓉", "张无忌", "周芷若", "赵敏"] # 访问 print(roles) print("roles Num:", len(roles)) print(roles[0]) print(roles[1]) print(roles[2]) print('*' * 23) # 修改,添加,删除 roles[8] = "小昭" print(roles) print('*' * 23) roles.append("韦小宝") roles.append("阿珂") print(roles) roles.insert(0, "洪七公") print(roles) print('*' * 23) del roles[0] print(roles) roles.pop() print(roles) roles.pop(10) print(roles) roles.remove("小昭") print(roles) print('*' * 23) print(sorted(roles)) print(sorted(roles, reverse=True)) print(roles) print('*' * 23) roles.reverse() print(roles) roles.reverse() print(roles) roles.sort() print(roles) print('*' * 23) print("roles Num:", len(roles)) 执行结果: ['乔峰', '段誉', '虚竹', '杨过', '小龙女', '郭靖', '黄蓉', '张无忌', '周芷若', '赵敏'] roles Num: 10 乔峰 段誉 虚竹 *********************** ['乔峰', '段誉', '虚竹', '杨过', '小龙女', '郭靖', '黄蓉', '张无忌', '小昭', '赵敏'] *********************** ['乔峰', '段誉', '虚竹', '杨过', '小龙女', '郭靖', '黄蓉', '张无忌', '小昭', '赵敏', '韦小宝', '阿珂'] ['洪七公', '乔峰', '段誉', '虚竹', '杨过', '小龙女', '郭靖', '黄蓉', '张无忌', '小昭', '赵敏', '韦小宝', '阿珂'] *********************** ['乔峰', '段誉', '虚竹', '杨过', '小龙女', '郭靖', '黄蓉', '张无忌', '小昭', '赵敏', '韦小宝', '阿珂'] ['乔峰', '段誉', '虚竹', '杨过', '小龙女', '郭靖', '黄蓉', '张无忌', '小昭', '赵敏', '韦小宝'] ['乔峰', '段誉', '虚竹', '杨过', '小龙女', '郭靖', '黄蓉', '张无忌', '小昭', '赵敏'] ['乔峰', '段誉', '虚竹', '杨过', '小龙女', '郭靖', '黄蓉', '张无忌', '赵敏'] *********************** ['乔峰', '小龙女', '张无忌', '杨过', '段誉', '虚竹', '赵敏', '郭靖', '黄蓉'] ['黄蓉', '郭靖', '赵敏', '虚竹', '段誉', '杨过', '张无忌', '小龙女', '乔峰'] ['乔峰', '段誉', '虚竹', '杨过', '小龙女', '郭靖', '黄蓉', '张无忌', '赵敏'] *********************** ['赵敏', '张无忌', '黄蓉', '郭靖', '小龙女', '杨过', '虚竹', '段誉', '乔峰'] ['乔峰', '段誉', '虚竹', '杨过', '小龙女', '郭靖', '黄蓉', '张无忌', '赵敏'] ['乔峰', '小龙女', '张无忌', '杨过', '段誉', '虚竹', '赵敏', '郭靖', '黄蓉'] *********************** roles Num: 9
列表操作
-
遍历列表
for循环实现
使用for 循环处理数据是一种对数据集执行整体操作的不错的方式
主要注意: 避免缩进错误,不要遗漏冒号magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician.title() + ", that was a great trick!") print("I can't wait to see your next trick, " + magician.title() + ".\n") print("Thank you everyone, that was a great magic show!") 执行结果: Alice, that was a great trick! I can't wait to see your next trick, Alice. David, that was a great trick! I can't wait to see your next trick, David. Carolina, that was a great trick! I can't wait to see your next trick, Carolina. Thank you everyone, that was a great magic show!示例:
pizzas = ["海鲜至尊披萨", "奥尔良烤肉披萨", "榴莲芝士披萨", "西班牙火腿披萨", "鸡肉咖喱披萨"] for pizza in pizzas: print(pizza) print("*" * 23) for pizza in pizzas: print("我喜欢%s" % pizza) print("*" * 23) print("必胜客披萨:") i = 0 count = len(pizzas) for pizza in pizzas: i += 1 if i < count: print(pizza, end="、") else: print(pizza) print("我老婆非常喜欢吃披萨") 执行结果: 海鲜至尊披萨 奥尔良烤肉披萨 榴莲芝士披萨 西班牙火腿披萨 鸡肉咖喱披萨 *********************** 我喜欢海鲜至尊披萨 我喜欢奥尔良烤肉披萨 我喜欢榴莲芝士披萨 我喜欢西班牙火腿披萨 我喜欢鸡肉咖喱披萨 *********************** 必胜客披萨: 海鲜至尊披萨、奥尔良烤肉披萨、榴莲芝士披萨、西班牙火腿披萨、鸡肉咖喱披萨 我老婆非常喜欢吃披萨 -
创建数值列表
- 函数range()
for value in range(1,6): print(value) 执行结果: 1 2 3 4 5- 创建数字列表
可使用函数list() 将range() 的结果直接转换为列表
numbers = list(range(1,6)) print(numbers) 执行结果: [1, 2, 3, 4, 5]函数range() 时,还可指定步长
even_numbers = list(range(2,11,2)) print(even_numbers) 执行结果: [2, 4, 6, 8, 10]squares = [] for value in range(1,11): square = value**2 squares.append(square) print(squares) 执行结果: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]- 数字列表执行简单统计
min(), max(), sum() 使用与数字列表,其实使用与任何列表?
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] print("Min: {}".format(min(digits))) print("Max: {}".format(max(digits))) print("Sum:{}".format(sum(digits))) 执行结果: Min: 0 Max: 9 Sum:45- 列表解析
列表解析 将for 循环和创建新元素的代码合并成一行,并自动附加新元素。
定义一个表达式,编写一个for 循环,用于给表达式提供值
注意:这里的for 语句末尾没有冒号。
squares = [value**2 for value in range(1,11)] print(squares) 执行结果: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]示例:
for i in range(1, 11): print(i) 执行结果: 1 2 3 4 5 6 7 8 9 10 number = list(range(1,11)) for i in number: print(i) 执行结果: 1 2 3 4 5 6 7 8 9 10 number = list(range(1,1000001)) print("min():", min(number)) print("max():", max(number)) print("sum():", sum(number)) 执行结果: min(): 1 max(): 1000000 sum(): 500000500000 odd = list(range(1, 20, 2)) for i in odd: print(i) 执行结果: 1 3 5 7 9 11 13 15 17 19 multiples3 = list(range(3, 30, 3)) for i in multiples3: print(i) 执行结果: 3 6 9 12 15 18 21 24 27 cubes = [] for i in range(1, 11): cube = i ** 3 cubes.append(cube) print(cubes) cubes = [i ** 3 for i in range(1, 11)] print(cubes) 执行结果: [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] -
列表切片
列表部分元素, python称之为切片- 切片
要创建切片, 可指定要使用的第一个元素和最后一个元素的索引。 与函数range() 一样, Python在到达你指定的第二个索引前面的元素后停止。 要输出列表中的前三个元素, 需
要指定索引0~3, 这将输出分别为0 、 1 和2 的元素。
players = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[0:3]) print(players[1:4]) print(players[:4]) # 未指定第一个索引,自动从列表开头开始获取 print(players[2:]) # 未指定第二个索引,自动获取到列表末尾 print(players[-3:]) # 负数索引返回离列表末尾相应距离的元素 执行结果: ['charles', 'martina', 'michael'] ['martina', 'michael', 'florence'] ['charles', 'martina', 'michael', 'florence'] ['michael', 'florence', 'eli'] ['michael', 'florence', 'eli']切片其实还有一个步长参数,后续单独补充!!!
- 遍历切片
players = ['charles', 'martina', 'michael', 'florence', 'eli'] print("Here are the first three players on my team:") for player in players[:3]: print(player.title()) 执行结果: Here are the first three players on my team: Charles Martina Michael- 复制列表
要复制列表, 可创建一个包含整个列表的切片, 方法是同时省略起始索引和终止索引( [:] ) 。 这让Python创建一个始于第一个元素, 终止于最后一个元素的切片, 即复制整个列表。
赋值不会产生新列表
# 赋值 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']复制列表
# 复制 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']示例:
pizzas = ["海鲜至尊披萨", "奥尔良烤肉披萨", "榴莲芝士披萨", "西班牙火腿披萨", "鸡肉咖喱披萨"] print("列表前三个元素:", pizzas[:3]) print("列表中间三个元素", pizzas[1:-1]) print("列表后三个元素:", pizzas[-3:]) 执行结果: 列表前三个元素: ['海鲜至尊披萨', '奥尔良烤肉披萨', '榴莲芝士披萨'] 列表中间三个元素 ['奥尔良烤肉披萨', '榴莲芝士披萨', '西班牙火腿披萨'] 列表后三个元素: ['榴莲芝士披萨', '西班牙火腿披萨', '鸡肉咖喱披萨'] pizzas = ["海鲜至尊披萨", "奥尔良烤肉披萨", "榴莲芝士披萨", "西班牙火腿披萨", "鸡肉咖喱披萨"] friend_pizzas = pizzas[:] pizzas.append("牛肉咖喱披萨") friend_pizzas.append("羊肉芝士披萨") print(pizzas) print(friend_pizzas) print("我喜欢的披萨:") for pizza in pizzas: print(pizza) print("*" * 23) print("我朋友喜欢的披萨:") for pizza in friend_pizzas: print(pizza) 执行结果: ['海鲜至尊披萨', '奥尔良烤肉披萨', '榴莲芝士披萨', '西班牙火腿披萨', '鸡肉咖喱披萨', '牛肉咖喱披萨'] ['海鲜至尊披萨', '奥尔良烤肉披萨', '榴莲芝士披萨', '西班牙火腿披萨', '鸡肉咖喱披萨', '羊肉芝士披萨'] 我喜欢的披萨: 海鲜至尊披萨 奥尔良烤肉披萨 榴莲芝士披萨 西班牙火腿披萨 鸡肉咖喱披萨 牛肉咖喱披萨 *********************** 我朋友喜欢的披萨: 海鲜至尊披萨 奥尔良烤肉披萨 榴莲芝士披萨 西班牙火腿披萨 鸡肉咖喱披萨 羊肉芝士披萨 - 切片
元组(不可变)
列表非常适合用于存储在程序运行期间可能变化的数据集。 列表是可以修改的。
有时候需要创建一系列不可修改的元素, 元组可以满足这种需求。
Python将不能修改的值称为不可变的 , 而不可变的列表被称为元组 。
元组定义
元组看起来犹如列表, 但使用圆括号而不是方括号来标识。
定义元组后, 就可以使用索引来访问其元素, 就像访问列表元素一样。
()构建,里面的元素可以是不同类型,也可以嵌套
-
定义元组
dimensions = (200, 50) print(dimensions[0]) print(dimensions[1]) 执行结果: 200 50 dimensions[0] = 250 执行结果: Traceback (most recent call last): File "XXXX", line XX, in <module> dimensions[0] = 250 TypeError: 'tuple' object does not support item assignment -
元组运算
+加拼接
*乘重复
-减不存在, TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'
2.1 + 加 拼接foods1 = ("龙虾", "三文鱼", "牛肉") foods2 = ("大闸蟹", "西班牙火腿") foods = foods1+ foods2 print(foods) 执行结果: ('龙虾', '三文鱼', '牛肉', '大闸蟹', '西班牙火腿')2.2 * 乘 重复
foods = ("龙虾", "三文鱼", "牛肉") print(foods * 3) 执行结果: ('龙虾', '三文鱼', '牛肉', '龙虾', '三文鱼', '牛肉', '龙虾', '三文鱼', '牛肉') -
遍历元组中的所有值
dimensions = (200, 50) for dimension in dimensions: print(dimension) 执行结果: 200 50 -
修改元组变量
虽然不能修改元组的元素, 但可以给存储元组的变量赋值dimensions = (200, 50) print("Original dimensions:") for dimension in dimensions: print(dimension) dimensions = (400, 100) print("\nModified dimensions:") for dimension in dimensions: print(dimension) 执行结果: Original dimensions: 200 50 Modified dimensions: 400 100示例:
foods = ("龙虾", "三文鱼", "牛肉", "大闸蟹", "西班牙火腿") for food in foods: print(food) # foods[4] = "生菜" # Traceback (most recent call last): # File "ch04.py", line 180, in <module> # foods[4] = "生菜" # TypeError: 'tuple' object does not support item assignment print("*" * 23) foods = ("龙虾", "三文鱼", "羊肉", "大闸蟹", "生菜") for food in foods: print(food) 执行结果: 龙虾 三文鱼 牛肉 大闸蟹 西班牙火腿 *********************** 龙虾 三文鱼 羊肉 大闸蟹 生菜- 元组相关补充说明
-
定义空元组,以及定义只有一个元素的元组
定义一个空的tuple,可以写成():>>> t = () >>> t ()要定义一个只有1个元素的tuple,如果你这么定义:
>>> t = (1) >>> t 1定义的不是tuple,是1这个数!这是因为括号()既可以表示tuple,又可以表示数学公式中的小括号,这就产生了歧义,因此,Python规定,这种情况下,按小括号进行计算,计算结果自然是1。
所以,只有1个元素的tuple定义时必须加一个逗号,,来消除歧义:
>>> t = (1,) >>> t (1,)Python在显示只有1个元素的tuple时,也会加一个逗号,,以免你误解成数学计算意义上的括号。
-
“可变的”tuple
>>> t = ('a', 'b', ['A', 'B']) >>> t[2][0] = 'X' >>> t[2][1] = 'Y' >>> t ('a', 'b', ['X', 'Y'])这个tuple定义的时候有3个元素,分别是'a','b'和一个list。不是说tuple一旦定义后就不可变了吗?怎么后来又变了?
先看看定义的时候tuple包含的3个元素:
image.png当我们把list的元素'A'和'B'修改为'X'和'Y'后,tuple变为:
image.png
表面上看,tuple的元素确实变了,但其实变的不是tuple的元素,而是list的元素。tuple一开始指向的list并没有改成别的list,所以,tuple所谓的“不变”是说,tuple的每个元素,指向永远不变。即指向'a',就不能改成指向'b',指向一个list,就不能改成指向其他对象,但指向的这个list本身是可变的!
不可变的理解:对应元素内存地址不可变。如果元组中包含可变元素(如列表),那么这个可变元素(如列表)里面包含的元素是可变的
理解了“指向不变”后,要创建一个内容也不变的tuple怎么做?那就必须保证tuple的每一个元素本身也不能变。
参考:
相关互联网文档


