《Python编程 从入门到实践》-基础知识总结3

84 阅读7分钟

操作列表

  • 遍历整个列表

  • 避免缩进错误

  • 创建数值列表

  • 切片—列表的一部分

  • 无法变值的—元组

  • 设置代码格式 \


遍历整个列表

下面使用for循环来打印每一个字母:

words= ['a', 'b', 'c']
for word in words:
    print(word)

这行代码让Python从列表words中取出一个字母(一个一个取),并将其存储在变量word中。最后,我们让Python打印前面存储到变量word中的字母(有空行)。

a
b
c
避免缩进错误

Python通过使用缩进让代码更易读;简单地说,它要求你使用缩进让代码整洁而结构清晰。在较长的Python程序中,你将看到缩进程度各不相同的代码块,这让你对程序的组织结构有大致的认识。常见缩进错误:

  • 忘记缩进
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
  • 忘记缩进额外的代码行
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")
  • 不必要的缩进
message = "Hello Python world!"
  print(message)
  • 循环后不必要的缩进
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!")
  • 遗漏了冒号
magicians = ['alice', 'david', 'carolina']
for magician in magicians
    print(magician)
创建数值列表

 使用函数range() 
使用range()创建数字列表 
对数字列表执行简单的统计计算 
列表解析

  • 使用函数range()

Python函数range()让你能够轻松地生成一系列的数字。例如,可以像下面这样使用函数range()来打印一系列的数字:

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

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

1
2
3
4

在这个示例中,range()只是打印数字1~4,这是你在编程语言中经常看到的差一行为的结果。函数range()让Python从你指定的第一个值开始数,并在到达你指定的第二个值后停止,因此输出不包含第二个值(这里为5)。 
要打印数字1~5,需要使用range(1,6)。

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

要创建数字列表,可使用函数list()将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]

下面的代码演示了如何将前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]
  • 对数字列表执行简单的统计计算
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits)) #min 0
print(max(digits)) #max 9 
print(sum(digits)) #sum 45
  • 列表解析

前面介绍的生成列表squares的方式包含三四行代码,而列表解析让你只需编写一行代码就能生成这样的列表。列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素。

下面的示例使用列表解析创建你在前面看到的平方数列表:

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

首先指定一个描述性的列表名,如squares;然后,指定一个左方括号,并定义一个表达式,用于生成你要存储到列表中的值。在这个示例中,表达式为value**2,它计算平方值。接下来,编写一个for循环,用于给表达式提供值,再加上右方括号。 
结果与你在前面看到的平方数列表相同:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
使用列表的一部分

 切片 
遍历切片 
复制列表

  • 切片

要创建切片,可指定要使用的第一个元素和最后一个元素的索引。与函数range()一样,Python在到达你指定的第二个索引前面的元素后停止。要输出列表中的前三个元素,需要指定索引0~3,这将输出分别为0、1和2的元素。

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

输出也是一个列表,其中包含前三名队员:

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

如果你没有指定第一个索引,Python将自动从列表开头开始:

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

由于没有指定起始索引,Python从列表开头开始提取:

# ['charles', 'martina', 'michael', 'florence']

要让切片终止于列表末尾,也可使用类似的语法。例如,如果要提取从第3个元素到列表末尾的所有元素,可将起始索引指定为2,并省略终止索引:

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

Python将返回从第3个元素到列表末尾的所有元素:

# ['michael', 'florence', 'eli']

无论列表多长,这种语法都能够让你输出从特定位置到列表末尾的所有元素。

  • 遍历切片

如果要遍历列表的部分元素,可在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())

代码没有遍历整个队员列表,而只遍历前三名队员:

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_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_foods赋给friend_foods,而不是将my_foods的副本存储到friend_foods 
这种语法实际上是让Python将新变量friend_foods关联到包含在my_foods中的列表,因此这两个变量都指向同一个列表。鉴于此,当我们将’cannoli’添加到my_foods中时,它也将出现在friend_foods中;同样,虽然’ice cream’好像只被加入到了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']
元组

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

定义元组 
遍历元组中的所有值 
修改元组变量

  • 定义元组

元组看起来犹如列表,但使用圆括号而不是方括号来标识。定义元组后,就可以使用索引来访问其元素,就像访问列表元素一样。

dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
#200
#50
  • 遍历元组中的所有值

像列表一样,也可以使用for循环来遍历元组中的所有值:

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)

我们首先定义了一个元组,并将其存储的尺寸打印了出来);接下来,将一个新元组存储到变量dimensions中;然后,打印新的尺寸。这次,Python不会报告任何错误,因为给元组变量赋值是合法的:

Original dimensions:
200
50

Modified dimensions:
400
100

相比于列表,元组是更简单的数据结构。如果需要存储的一组值在程序的整个生命周期内都不变,可使用元组。

设置代码格式
  • 格式设置指南PEP 8
  • 缩进——PEP 8建议每级缩进都使用四个空格
  • 行长——很多Python程序员都建议每行不超过80字符
  • 空行——要将程序的不同部分分开,可使用空行