Python3:基本语法之二(列表、元组)

列表

在Python中,用方括号"[ ]"来表示列表,并用逗号来分隔其中的元素。下面是一个简单的列表示例,这个列表包含几种自行车:

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

输出结果(包括方括号一起打印):

['trek', 'cannondale', 'redline', 'specialized']

访问列表元素

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

当请求获取列表元素时,Python只返回该元素,而不包括方括号和引号,
输出结果为:

trek

索引值

在Python中,第一个列表元素的索引为0,而不是1。通过将索引指定为 -1 ,可让Python返回最后一个列表元素:

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

这些代码返回 ‘specialized’,索引-2返回倒数第二个列表元素,索引-3返回倒数第三个列表元素,以此类推。

使用列表的值

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
message = "My first bicycle was a " + bicycles[0].title() + "."

print(message)

输出结果为:

My first bicycle was a Trek.

修改列表元素

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

motorcycles[0] = 'ducati'
print(motorcycles)

输出结果:

['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']

在列表中添加元素

(列表初始状态也可以为空)

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

motorcycles.append('ducati')
print(motorcycles)

输出结果为:

['honda', 'yamaha', 'suzuki']
['honda', 'yamaha', 'suzuki', 'ducati']

在列表中插入元素

motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')

print(motorcycles)

输出结果为:

['ducati', 'honda', 'yamaha', 'suzuki']

从列表中删除元素

1.使用 del 语句删除元素:如果知道要删除的元素在列表中的位置,可使用 del 语句。

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

del motorcycles[0]
print(motorcycles)

输出结果为:

['honda', 'yamaha', 'suzuki']
['yamaha', 'suzuki']

2.使用方法 pop() 删除元素:你要将元素从列表中删除,并接着使用它的值。

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

popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)

输出结果为:

['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki

3.弹出列表中任何位置处的元素:你可以使用 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.

4.根据值删除元素:有时候,你不知道要从列表中删除的值所处的位置。如果你只知道要删除的元素的值,可使用方法 remove() 。
假设要从列表 motorcycles 中删除值 ‘ducati’ :

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

motorcycles.remove('ducati')
print(motorcycles)

让Python确定 ‘ducati’ 出现在列表的什么地方,并将该元素删除:

['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']

方法 remove() 只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值。

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

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

方法sort()永久性地修改了列表元素的排列顺序。现在,汽车是按字母顺序排列的。
输出结果:

['audi', 'bmw', 'subaru', 'toyota']

反序:

cars = ['bmw', 'audi', 'toyota', 'subaru']

cars.sort(reverse=True)
print(cars)

同样,对列表元素排列顺序的修改是永久性的:

['toyota', 'subaru', 'bmw', 'audi']

使用函数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 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 original list again:
['bmw', 'audi', 'toyota', 'subaru']

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

倒着打印列表

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

cars.reverse()
print(cars)

注意, reverse() 不是指按与字母顺序相反的顺序排列列表元素,而只是反转列表元素的排列顺序:

['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']

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

确定列表的长度

使用函数 len() 可快速获悉列表的长度。在下面的示例中,列表包含4个元素,因此其长度为4:

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

遍历整个列表

Python靠缩进确定包含关系

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

使用函数range()

可以像下面这样使用函数range()来打印一系列的数字:

for value in range(1,5):
	print(value)

上述代码好像应该打印数字1~5,但实际上它不会打印数字5:

1
2
3
4

使用 range() 创建数字列表

如果将 range() 作为list() 的参数,输出将为一个数字列表。

numbers = list(range(1,6))
print(numbers)

输出结果:

[1, 2, 3, 4, 5]

使用函数 range() 时,还可指定步长。例如,下面的代码打印1~10内的偶数:

even_numbers = list(range(2,11,2))
print(even_numbers)

在这个示例中,函数range()从2开始数,然后不断地加2,直到达到或超过终值11,因此
输出如下:

[2, 4, 6, 8, 10]

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

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

列表解析

squares = [value**2 for value in range(1,11)]
print(squares)

for 循环为 for value in range(1,11) ,它将值1~10提供给表达式 value**2 。请注意,这里的 for语句末尾没有冒号。
输出结果:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

切片

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

代码打印该列表的一个切片,其中只包含三名队员。输出也是一个列表,其中包含前三名队员:

['charles', 'martina', 'michael']

遍历切片

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

复制列表

注意:friend_foods = my_foods这种方法行不通,会同时影响两边。

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']

元组

Python将不能修改的值称为不可变的,不可变的列表被称为元组

dimensions = (200, 50)
dimensions[0] = 250		# 错误,Python指出不能给元组的元素赋值

遍历元组中的所有值

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

R-QWERT

你的鼓励是我最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值