《python编程从入门到实践》2-4章
第 2 章 变量和简单的数据类型
2.3 字符串
2.3.1 title/upper/lower大小写
name = "ada lovelace"
print(name) # ada lovelace
print(name.title()) # Ada Lovelace
print(name.upper()) # ADA LOVELACE
print(name.lower()) # ada lovelace
2.3.2 f插值(字符串中使用变量)
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(full_name) # ada lovelace
print(f"Hello, {full_name.title()}!") # Hello, Ada Lovelace!
2.3.3 \t使用制表符或换行符来添加空白
空白泛指任何非打印字符,如空格(' ')、制表符(\t)和换行符(\n)。
# 打印空格
print("这里有一个空格:' '")
# 打印制表符(\t),用于缩进或对齐文本
print("使用制表符进行缩进:\t这是缩进后的内容")
# 打印换行符(\n),用于在文本中换行
print("这是第一行内容\n这是第二行内容")
# 输出:
# 这里有一个空格:' '
# 使用制表符进行缩进: 这是缩进后的内容
# 这是第一行内容
# 这是第二行内容
2.3.4 lstrip/rstrip删除空白
删除字符串左端的空白或同时删除字符串两端的空白,分别使用 lstrip() 方法和 strip() 方法
favorite_language = 'python '
print(f"1.({favorite_language})")
print(f"2.({favorite_language.rstrip()})") # favorite_language 暂时删除空白
print(f"3.({favorite_language})")
print('-----')
favorite_language = favorite_language.rstrip() # favorite_language 永久删除空白
print(f"4.({favorite_language})")
#1.(python )
#2.(python)
#3.(python )
#-----
#4.(python)
2.3.5 removeprefix删除前缀/removesuffix删除后缀
nostarch_url = 'https://nostarch.com'
print(nostarch_url.removeprefix('https://')) # nostarch.com
删除后缀
filename = 'python_notes.txt'
print(filename.removesuffix(".txt")) //removesuffix
2.4 数字
2.4.1 整数
number1 = 2*6 # 2 乘以 6
print(number1)
number2 = 2**6 # 2的6次方
print(number2)
2.4.2 浮点数(float)
需要注意的是,结果包含的小数位数可能是不确定的
number3 = 0.3 + 0.2
print(number3) # 0.5
number4 = 0.1 + 0.2
print(number4) # 0.30000000000000004
number5 = 0.1 * 3
print(number5) # 0.30000000000000004
2.4.3 整数和浮点数
将任意两个数相除,结果总是浮点数
>>> 4/2
2.0
2.4.4 数中的下划线
在书写很大的数时,可使用下划线将其中的位分组,使其更清晰易读
universe_age = 14_000_000_000
print(universe_age) # 14000000000
universe_age = 24_0_0000_0000
print(universe_age) # 24000000000
2.4.5 同时给多个变量赋值
>>> x, y, z = 0, 0, 0
2.4.6 常量
使用全大写字母来指出应将某个变量视为常量
MAX_CONNECTIONS = 5000
第 3 章 列表简介
3.1 列表访问
3.1.1 访问列表元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0]) # trek
3.1.3 使用列表中的各个值
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
message = f"My first bicycle was a {bicycles[0].title()}."
print(message)
# My first bicycle was a Trek.
3.2 修改、添加和删除元素
3.2.1 修改
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
# ['honda', 'yamaha', 'suzuki']
# ['ducati', 'yamaha', 'suzuki']
3.2.2 新增 append / insert
末尾新增append
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)
插入元素insert
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
# ['ducati', 'honda', 'yamaha', 'suzuki']
3.2.3 删除 del / pop() / remove()
下面是一个简单的判断标准:如果要从列表中删除一个元素,且不再以任何方式使用它,就使用 del 语句;如果要在删除元素后继续使用它,就使用 pop() 方法
01 del 删除
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
02 pop() 方法删除列表末尾的元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles) # ['honda', 'yamaha']
print(popped_motorcycle) # suzuki
方法 pop() 有什么用处呢?假设列表中的自行车是按购买时间存储的,就可使用方法 pop() 来打印一条消息,指出最后购买的是哪款自行车:
motorcycles = ['honda', 'yamaha', 'suzuki']
last_owned = motorcycles.pop()
print(f"The last motorcycle I owned was a {last_owned.title()}.")
print(motorcycles) # ['honda', 'yamaha']
03 删除列表中任意位置的元素
也可以使用 pop() 删除列表中任意位置的元素
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
print(f"The first motorcycle I owned was a {first_owned.title()}.")
04 根据值删除元素 remove()
注意:remove() 方法只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环,确保将每个值都删除。
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
使用remove() 删除的值可以继续使用
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
too_expensive = 'ducati'
motorcycles.remove(too_expensive)
print(motorcycles)
print(f"\nA {too_expensive.title()} is too expensive for me.")
# ['honda', 'yamaha', 'suzuki', 'ducati']
# ['honda', 'yamaha', 'suzuki']
#A Ducati is too expensive for me.
3.3 管理列表
3.3.1 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']
3.3.2 sorted()临时排序
也可向 sorted() 函数传递参数 reverse=True
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("\nHere is the sorted list:")
print(sorted(cars)) # ['audi', 'bmw', 'subaru', 'toyota']
print("\nHere is the original list again:")
print(cars) # ['bmw', 'audi', 'toyota', 'subaru']
3.3.3 reverse() 反向打印列表
reverse() 不是按与字母顺序相反的顺序排列列表元素
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)
3.4 使用列表时避免索引错误
每当需要访问最后一个列表元素时,都可以使用索引 -1。这在任何情况下都行之有效,即便在你最后一次访问列表后,其长度发生了变化
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles[-1])
仅当列表为空时,这种访问最后一个元素的方式才会导致错误
motorcycles = []
print(motorcycles[-1])
下面报错
File "e:\C sharp电子书\电子书\python\python学习\3.3 管理列表.py", line 19, in <module>
print(motorcycles[-1])
~~~~~~~~~~~^^^^
IndexError: list index out of range
第 4 章 操作列表
4.1 遍历列表
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
执行多行
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
print("1")
print("2")
#alice
# 1
# david
# 1
# carolina
# 1
# 2
4.3 创建数值列表
4.3.1 使用 range() 函数
要创建数值列表,可使用 list() 函数将 range() 的结果直接转换为列表
for value in range(1, 5):
print(value)
# 1,2,3,4
4.3.2 使用 range() 创建数值列表
numbers = list(range(1, 6))
print(numbers)
# [1, 2, 3, 4, 5]
使用 range() 函数时,还可指定步长。为此,可以给这个函数指定第三个参数,Python 将根据这个步长来生成数
even_numbers = list(range(2, 11, 2)) # 从2-10,不断+2
print(even_numbers) # [2, 4, 6, 8, 10]
4.3.3 对数值列表执行简单的统计计算
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits))
# 0
print(max(digits))
# 9
print(sum(digits))
# 45
4.3.4 列表推导式
列表推导式(list comprehension)将 for 循环和创建新元素的代码合并成一行,并自动追加新元素
例如,如何创建一个列表,其中包含前 10 个整数(1~10)的平方
# 普通
squares1 = []
for value in range(1,11):
squares1.append(value**2)
print(squares1)
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 2 列表推导式
squares2 = [value**2 for value in range(1, 11)]
print(squares2)
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
要使用这种语法,首先指定一个描述性的列表名,如 squares。然后指定一个左方括号,并定义一个表达式,用于生成要存储到列表中的值。

4.4 使用列表的一部分
4.4.1 切片
要输出列表中的前三个元素,需要指定索引 0 和 3
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
# 从第0个到第2个 ['charles', 'martina', 'michael']
例如,如果要提取列表的第二、第三和第四个元素,
print(players[1:4])
# 从第1个到第3个 ['martina', 'michael', 'florence']
如果没有指定第一个索引,Python 将自动从列表开头开始:
print(players[:4])
# 从第0个开始到第3个 ['charles', 'martina', 'michael', 'florence']
要让切片终止于列表末尾,也可使用类似的语法。
print(players[2:])
# 从第2个开始到结束: ['michael', 'florence', 'eli']
负数索引返回与列表末尾有相应距离的元素,因此可以输出列表末尾的任意切片。如果要输出名单上最后三名队员的名字,可使用切片 players[-3:]:
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:])
# 从倒数第3个开始到结束: ['michael', 'florence', 'eli']
4.4.2 遍历切片
如果要遍历列表的部分元素,可在 for 循环中使用切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
4.4.3 复制列表
要复制列表,可以创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:])。这让 Python 创建一个起始于第一个元素、终止于最后一个元素的切片,即复制整个列表。
# 复制
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print("My favorite foods are:")
my_foods[0] = "caomei"
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
#My favorite foods are:
#['caomei', 'falafel', 'carrot cake']
#My friend's favorite foods are:
#['pizza', 'falafel', 'carrot cake']
4.5 元组
你有时候需要创建一系列不可修改的元素,元组可满足这种需求。Python 将不能修改的值称为不可变的,而不可变的列表称为元组(tuple)
4.5.1 定义元组
元组看起来很像列表,但使用圆括号而不是方括号来标识。定义元组后,就可使用索引来访问其元素,就像访问列表元素一样。
dimensions = (200, 50)
print(dimensions[0]) # 200
print(dimensions[1]) # 50
如果你要定义只包含一个元素的元组,必须在这个元素后面加上逗号:
my_t = (3,)
4.5.3 修改元组变量
虽然不能修改元组的元素,但可以给表示元组的变量赋值。
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

浙公网安备 33010602011771号