啊,但是for i in array遍历每个元素,所以if i < len(item)-1:比较一个字符串(数组元素item)和一个整数(len(item)-1:)。
所以,问题是您误解了Python中的how ^{} works。
快速修复?
您可以将for替换为for i in range(len(array)),因为range的工作方式如下:>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
从而获得:spam = ['apples', 'bananas', 'tofu', 'cats']
def printSpam(item):
for i in range(len(item)):
if i < len(item)-1:
print (','.join(str(item[i])))
else:
print ("and ".join(str(item[len(item)-1])))
return
printSpam(spam)
不过,输出可能不会是您所期望的那样,因为'c'.join(array)在数组的各个元素之间使用'c'作为“粘合剂”,如果不是字符数组,那么什么是字符串?>>> ','.join("bananas")
'b,a,n,a,n,a,s'
因此,输出将是:a,p,p,l,e,s
b,a,n,a,n,a,s
t,o,f,u
cand aand tand s
我们无论如何都可以做得更好。
Python支持所谓的slice notation和负索引(从数组末尾开始)。
自从>>> spam[0:-1]
['apples', 'bananas', 'tofu']
>>> spam[-1]
'cats'
我们有那个>>> ", ".join(spam[0:-1])
'apples, bananas, tofu'
以及>>> ", ".join(spam[0:-1]) + " and " + spam[-1]
'apples, bananas, tofu and cats'
因此,您可以简单地编写函数def printSpam(item):
print ", ".join(item[0:-1]) + " and " + item[-1]
就这样。
它起作用了。
附:关于Python和数组表示法的一件事是:>>> "Python"[::-1]
'nohtyP'