Python:<str和int之间不支持

0 python syntax

我正在通过Automate the Boring Stuff学习Python,而且我遇到了一些我不太了解的东西.

我正在尝试创建一个简单的for循环,以这种格式打印列表的元素:W, X, Y, and Z.

我的代码如下所示:

spam = ['apples', 'bananas', 'tofu', 'cats']

def printSpam(item):
    for i in item:
        if i < len(item)-1:
            print (','.join(str(item[i])))
        else:
            print ("and ".join(str(item[len(item)-1])))
    return

printSpam(spam)
Run Code Online (Sandbox Code Playgroud)

我得到这个错误作为回应:

Traceback (most recent call last):
  File "CH4_ListFunction.py", line 11, in <module>
    printSpam(spam)
  File "CH4_ListFunction.py", line 5, in printSpam
    if i < len(item)-1:
TypeError: '<' not supported between instances of 'str' and 'int'
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏.谢谢你帮助一个新手.

Tob*_*san 5

啊,但for i in array迭代每个元素,所以if i < len(item)-1:比较一个字符串(数组元素item)和一个整数(len(item)-1:).

所以,问题是你误解for Python的工作原理.

快速修复?

你可以替换你forfor i in range(len(array)),range如下所示:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)

从而获得:

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)
Run Code Online (Sandbox Code Playgroud)

输出可能不会是你所期望的,因为'c'.join(array)在数组的各个元素之间使用'c'作为"粘合剂" - 什么是字符串,如果不是字符数组?

>>> ','.join("bananas")
'b,a,n,a,n,a,s'
Run Code Online (Sandbox Code Playgroud)

因此,输出将是:

a,p,p,l,e,s
b,a,n,a,n,a,s
t,o,f,u
cand aand tand s
Run Code Online (Sandbox Code Playgroud)

无论如何我们可以做得更好.

Python支持所谓的切片表示法和负索引(从数组的末尾开始).

以来

>>> spam[0:-1]
['apples', 'bananas', 'tofu']
>>> spam[-1]
'cats'
Run Code Online (Sandbox Code Playgroud)

我们有

>>> ", ".join(spam[0:-1])
'apples, bananas, tofu'
Run Code Online (Sandbox Code Playgroud)

>>> ", ".join(spam[0:-1]) + " and " + spam[-1]
'apples, bananas, tofu and cats'
Run Code Online (Sandbox Code Playgroud)

因此,您可以简单地编写您的函数

def printSpam(item):
    print ", ".join(item[0:-1]) + " and " + item[-1]
Run Code Online (Sandbox Code Playgroud)

而已.有用.

PS:关于Python和数组表示法的一件事:

>>> "Python"[::-1]
'nohtyP'
Run Code Online (Sandbox Code Playgroud)

  • 这实际上是我在Python中阅读"for"符号的最具信息性的解释,我有点尴尬,我在代码中忘记了`range()`函数; CodeAcademy至少教会了我这一点.我将回去尝试不同的代码练习,看看这次我是否可以创造不同的东西.感谢您的答复! (2认同)