>>> from env_helper import info; info()
页面更新时间: 2024-01-14 09:36:11
运行环境:
    Linux发行版本: Debian GNU/Linux 12 (bookworm)
    操作系统内核: Linux-6.1.0-16-amd64-x86_64-with-glibc2.36
    Python版本: 3.11.2

4.2. 使用列表

当你第一次开始编程时,很容易会创建许多独立的变量, 来保存一组类似的值。例如,如果要保存我的猫的名字, 可能会写出这样的代码:

>>> catNamel ='Zophie'
>>> catName2 = 'Pooka'
>>> catName3 = 'Simon'
>>> catName4 = 'Lady Macbeth'
>>> catName5 = 'Fat-tail'
>>> catName6 = 'Miss Cleo'

事实表明这是一种不好的编程方式。 举一个例子,如果猫的数目发生改变, 程序就不得不增加变量,来保存更多的猫。 这种类型的程序也有很多重复或几乎相等的代码。 考虑下面的程序中有多少重复代码, 在文本编辑器中输入它并保存为 allMyCats1.py :

>>> print('Enter the name of cat 1:')
>>> catNamel = input()
>>> print( 'Enter the name of cat 2:')
>>> catName2 = input()
>>> print( 'Enter the name of cat 3:')
>>> catName3 = input()
>>> print( 'Enter the name of cat 4:')
>>> catName4 = input()
>>> print('Enter the name of cat 5:')
>>> catName5 = input()
>>> print('Enter the name of cat 6:')
>>> catName6 = input()
>>> print('The cat names are:')
>>> print(catNamel + ' ' + catName2 + ' ' + catName3 + ' ' +
>>> catName4 + ' '  + catName5 + ' ' + catName6)
Enter the name of cat 1:
2
Enter the name of cat 2:
4
Enter the name of cat 3:
64
Enter the name of cat 4:
45
Enter the name of cat 5:
435
Enter the name of cat 6:
4
The cat names are:
2 4 64 45 435 4

不必使用多个重复的变量,你可以使用单个变量, 包含一个列表值。例如, 下面是新的改进版本的 allMyCats1.py 程序。 这个新版本使用了一个列表, 可以保存用户输入的任意多的猫。在新的文件编辑器窗口中, 输入以下代码并保存为 allMyCats2.py

catNames =[]
while True:
    print('Enter the name of cat ' + str(len(catNames) + 1) + '(Or enter nothing to stop.): ')
    name = input()
    if name == '':
        break
    catNames = catNames + [name] # list concatenation
print('The cat names are: ')
for name in catNames:
    print( ' ' + name)

运行这个程序,输出看起来像这样:

Enter the name of cat 1 (Or enter nothing to stop.):
Zophie
Enter the name of cat 2 (Or enter nothing to stop.):
Pooka
Enter the name of cat 3 (Or enter nothing to stop.):
Simon
Enter the name of cat 4 (Or enter nothing to stop.):
Lady Macbeth
Enter the name of cat 5 (Or enter nothing to stop.):
Fat - tail
Enter the name of cat 6 (Or enter nothing to stop.):
Miss Cleo
Enter the name of cat 7 (Or enter nothing to stop.):

The cat names are:
    Zophie
    Pooka
    Simon
    Lady Macbeth
    Fat-tail
    Miss Cleo

使用列表的好处在于,现在数据放在一个结构中,所以程序能够更灵活的处理 数据,比放在一些重复的变量中方便。

4.2.1. 列表用于循环

从技术上说,循环是针对一个列表或类似列表中的每个值,重复地执行代码块。例如,如果执行以下代码:

>>> for i in range(4):
>>>     print(i)
0
1
2
3

这是因为 range(4) 的返回值是类似列表的值。 Python 认为它类似于 [0, 1,2, 3] 。 下面的程序和前面的程序输出相同:

>>> for i in [0, 1, 2, 3]:
>>>     print(i)
0
1
2
3

前面的 for 循环实际上是在循环执行它的子句,在每次迭代中,让变量依次设置为列表中的值。

一个常见的 Python 技巧,是在 for 循环中使用 range(len(someList)) , 迭代列表的每一个下标。例如,在交互式环境中输入以下代码:

>>> supplies = ['pens', 'staplers', 'flame-throwers', 'binders']
>>> for i in range(len(supplies)):
>>>     print('Index ' + str(i) + ' in supplies is: ' + supplies[i])
Index 0 in supplies is: pens
Index 1 in supplies is: staplers
Index 2 in supplies is: flame-throwers
Index 3 in supplies is: binders

在前面的循环中使用 range(len(supplies)) 很方便, 这是因为,循环中的代码可以访问下标(通过变量 i ),以及下标处的值(通过 supplies[i]) 。 最妙的是, range(len(supplies)) 将迭代 supplies 的所有下标,无论它包含多少表项。

更新的方式是使用 enumerate() 函数:

>>> for idx, item in enumerate(supplies):
>>>     print(idx, item)
0 pens
1 staplers
2 flame-throwers
3 binders

4.2.2. innot in 操作符

利用 innot in 操作符,可以确定一个值否在列表中。 像其他操作符一样 innot in 用在表达式中,连接两个值: 一个要在列表中查找的值,以及待查找的列表。 这些表达式将求值为布尔值。在交互式环境中输入以下代码:

>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']
True
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> 'cat' in spam
False
>>> 'howdy' not in spam
False
>>> 'cat' not in spam
True

例如,下面的程序让用户输入一个宠物名字,然后检查该名字是否在宠物列表中。打开一个新的文件编辑器窗口,输入以下代码,并保存为 myPets.py :

>>> myPets = ['Zophie', 'Pooka', 'Fat-tail']
>>> print( 'Enter a pet name:')
>>> name = input()
>>> if name not in myPets:
>>>     print( '1 do not have a pet named' + name)
>>> else:
>>>     print(name + ' is my pet.')
Enter a pet name:
Mao Da Bai
1 do not have a pet namedMao Da Bai

4.2.3. 多重赋值技巧

多重赋值技巧是一种快捷方式,让你在一行代码中,用列表中的值为多个变量 赋值。所以不必像这样:

>>> cat = ['fat', 'black', 'loud']
>>> size = cat[0]
>>> color = cat[1]
>>> disposition = cat[2]

而是输入下面的代码:

>>> cat = ['fat', 'black', 'loud']
>>> size, color, disposition = cat
>>> cat
['fat', 'black', 'loud']

变量的数目和列表的长度必须严格相等,否则 Python 将给出 ValueError :

cat = ['fat', 'black', 'loud']
size, color, disposition, name = cat

ValueError: not enough values to unpack (expected 4, got 3)

4.2.4. 利用切片取得子列表

就像下标可以从列表中取得单个值一样, “切片”可以从列表中取得多个值, 结果是一个新列表。切片输入在一对方括号中, 像下标一样,但它有两个冒号分隔 的整数。请注意下标和切片的不同。

  • spam[2] 是一个列表和下标(一个整数)。

  • spam[l:4]是一个列表和切片(两个整数)。

在一个切片中,第一个整数是切片开始处的下标。 第二个整数是切片结束处的下标。切片向上增长, 直至第二个下标的值,但不包括它。切片求值为一个新的列表值。 在交互式环境中输入以下代码:

>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>>
>>> spam[0:4]
['cat', 'bat', 'rat', 'elephant']
>>> spam[1:3]
['bat', 'rat']
>>> spam[0:-1]
['cat', 'bat', 'rat']

作为快捷方法,你可以省略切片中冒号两边的一个下标或两个下标。 省略第一个下标相当于使用 0 ,或列表的开始。 省略第二个下标相当于使用列表的长度, 意味着分片直至列表的末尾。

>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> spam[:2]
['cat', 'bat']
>>> spam[1:]
['bat', 'rat', 'elephant']
>>> spam[:]
['cat', 'bat', 'rat', 'elephant']