1. 逗号代码
假定有下面这样的列表:
spam = ['apples', 'bananas', 'tofu', 'cats']
编写一个函数,它以一个列表值作为参数,反馈一个字符串。该字符串包含所有表中的元素,元素之间以逗号和空格分隔,并在最后一个元素之前插入and。例如,将前面的spam列表传递给函数,将返回‘apples, bananas, tofu, and cats.’。但你的函数应该能够处理传递给它的任何列表。
版本1
def linkList(spam):
spam[-1] = 'and ' + spam[-1]
for i in spam[:-1]:
print(i, end = ', ')
print(spam[-1])
spam = ['apples', 'bananas', 'tufu', 'cats']
linkList(spam)
版本2
针对版本1中的linkList(spam)函数,当使用linkList([1, 2, 3, 4])时,显示为:
>>> linkList([1, 2, 3, 4])
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
linkList([1, 2, 3, 4])
File "D:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\练习\exercise4_10_1.py", line 2, in linkList
spam[-1] = 'and ' + spam[-1]
TypeError: must be str, not int
说明整型数据无法与字符串相连接,以上函数无法接收列表最后一位为整形数据的列表,故改为版本2,如下:
def linkList(spam):
spam.insert(len(spam) - 1,'and')
for i in spam[:-2]:
print(i, end = ', ')
print(str(spam[-2]) + ' ' + str(spam[-1]) + '.')
再次键入linkList([1, 2, 3, 4]),得到结果如下:
>>> linkList([1, 2, 3, 4])
1, 2, 3, and 4.