10-使用列表
4.2 使用列表
当你第一次开始编程时,很可能会创建许多独立的变量,来保存一组类似的值。例如,如果要保存你的猫的名字,可能会写出下面这样的代码:
catName1 = 'Zophie'
catName2 = 'Pooka'
catName3 = 'Simon'
catName4 = 'Lady Macbeth'
catName5 = 'Fat-tail'
catName6 = 'Miss Cleo'
事实表明,这是一种不好的编程方式。举一个例子,如果猫的数目发生改变,程序就不得不增加变量来保存更多的猫。这种类型的程序有很多重复或几乎相同的代码。考虑下面的程序中有多少重复代码,在文本编辑器中输入它并保存为allMyCats1.py:
print('Enter the name of cat 1:')
catName1 = 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(catName1 + ' ' + catName2 + ' ' + catName3 + ' ' + catName4 + ' ' +
catName5 + ' ' + catName6)
不必使用多个重复的变量,你可以使用单个变量,该变量包含一个列表值。例如,下面是新的改进版本的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
可以在https://autbor.com/allmycats1/和https://autbor.com/allmycats2/上查看这些程序的执行情况。使用列表的好处在于,现在数据放在一个结构中,因此程序能够更灵活地处理数据,比放在一些重复的变量中方便。