编程语言
首页 > 编程语言> > Python Crash Course读书笔记 - 第4章:WORKING WITH LISTS

Python Crash Course读书笔记 - 第4章:WORKING WITH LISTS

作者:互联网

遍历列表

使用for来遍历。

$ cat months.py
months=['jan','feb','march']
# 注意,months后的冒号(:)是必需的
for month in months:
# print之前必须缩进
        print(month)

特别注意,在print语句前必须有空格或<tab>键,不能顶头写,否则报错:

$ python3 months.py
  File "months.py", line 3
    print(m.title())
        ^
IndentationError: expected an indented block

运行结果如下:

$ python3 months.py
jan
feb
march

更进一步:

$ cat months.py
months=['jan','feb','march']
for month in months:
        print(f"the current month is {month.title()}.")

$ python3 months.py
the current month is Jan.
the current month is Feb.
the current month is March.

for循环后的语句,如果带缩进,则会重复执行,如果顶行首写(无缩进),则只执行一次。

$ cat months.py
months=['jan','feb','march']
for month in months:
        print(f"the current month is {month.title()}.")
        print('in loop')
print('not in loop')

$ python3 months.py
the current month is Jan.
in loop
the current month is Feb.
in loop
the current month is March.
in loop
not in loop

以下代码运行错误:

$ cat months.py
months=['jan','feb','march']
for month in months:
        print(f"the current month is {month.title()}.")
print('not in loop')
        print('in loop')

$ python3 months.py
  File "months.py", line 5
    print('in loop')
    ^
IndentationError: unexpected indent

避免缩进(identification)错误

Python使用缩进判读代码行是否相关,以使代码易读。
for循环后的语句至少有1行必须缩进。如果多行都需要循环,则这些行都需要缩进。这与C语言中的{}中的code block类似。

不必要的缩进同样会报错:

>>> a=1
>>>     print(a)
  File "<stdin>", line 1
    print(a)
    ^
IndentationError: unexpected indent

在for循环下,不必要的缩进会引起逻辑错误。
最后,for循环语句最后的冒号(:)是必需的。

数字列表

使用range函数。

>>> for i in range(1,5):
...     print(i)
...
1
2
3
4

range函数还可以指定步进值(step size):

>>> for i in range(1, 11, 2):
...     print(i)
...
1
3
5
7
9

注意5并不会被打印,因为其表示在5处停止。

由于函数是有返回值的,因此range可以用来给list赋值:

>>> numbers=range(1,5)
>>> print(numbers)
[1, 2, 3, 4]

以下函数打印平方表,其中**表示平方,另外首行的列表初始化为空是必要的:

$ cat squares.py
squares = []
for value in range(1, 11):
     squares.append(value ** 2)
print(squares)

$ python squares.py
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

部分统计函数:

>>> nums = [ 1, 2, 3, 4 ]
>>> min(nums)
1
>>> max(nums)
4
>>> sum(nums)
10
>>> sum(nums)/len(nums)
2.5

List Comprehensions将for循环和List赋值合成为一个语句:

>>> squares = [value*10 for value in range(1, 11)]
>>> print(squares)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

与List的一部分工作

切片

列表的一部分,两个参数分别表示开始于,结束于:

>>> seasons = ['spring', 'summer', 'autumn', 'winter']
>>> print(seasons[1:2])
['summer']
>>> print(seasons[2:4])
['autumn', 'winter']
# 如果第一个参数省略,则开始于第一个成员
>>> print(seasons[:4])
['spring', 'summer', 'autumn', 'winter']
# 如果最后一个参数省略,则结束于最后一个成员
>>> print(seasons[0:])
['spring', 'summer', 'autumn', 'winter']
>>> print(seasons[-3:])
['summer', 'autumn', 'winter']

List的部分也可用于for循环:

>>> for s in seasons[0:]:
...     print(s)
...
spring
summer
autumn
winter

拷贝

首先看一个失败的例子:

>>> seasons_copy=seasons
>>> print(seasons_copy)
['spring', 'summer', 'autumn', 'winter']
>>> seasons[0]='SPRING'
>>> print(seasons_copy)
['SPRING', 'summer', 'autumn', 'winter']

可以看到,这并不是拷贝,两个变量均指向同一List。

以下是正确的做法:

>>> seasons = ['spring', 'summer', 'autumn', 'winter']
>>> seasons_copy = seasons[:]
>>> seasons[0]='SPRING'
>>> print(seasons_copy)
['spring', 'summer', 'autumn', 'winter']

Tuple(元组)

不可改变(immutable)的List称为Tuple。
Tuple是用而非
List的成员包含在[]定义的。Tuple的成员用逗号(,)分割:

d=1,2,3,4

不过为了美观,也可以用()包围,如果只有一个成员,则()是必须的:


>>> d=(1,2,3,4)
>>> d=(1,)
>>>> d[0]=5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Tuple的遍历和List一样,此不赘述。
Tuple中的成员不能修改,但表示Tuple的变量可以修改,也就是可以指向新的Tuple。

代码风格

code is read more often than it is written

下面的建议来自Python Enhancement Proposal(PEP)。
使用4个空格而不是<tab>作为一个缩进
每行代码不要超过80字符
每行注释不要超过72字符
使用空行增强代码可读性

dingdingfish 博客专家 发布了352 篇原创文章 · 获赞 42 · 访问量 55万+ 他的留言板 关注

标签:summer,py,Crash,WORKING,读书笔记,months,month,print,seasons
来源: https://blog.csdn.net/stevensxiao/article/details/103979609