for in in range:TypeError:' type'对象不可迭代

时间:2016-10-21 09:39:14

标签: python

假设你有一个像这样的列表值:

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

编写一个以列表值作为参数的函数,并返回一个字符串,其中所有项由逗号和空格分隔,并带有'和'在最后一项之前插入。

例如,将前一个spam列表传递给函数将返回'apples, bananas, tofu, and cats',但您的函数应该能够处理传递给它的任何列表值

我的鳕鱼在下面。运行时,它显示TypeErrorprint(value, sep = ', ')无法正常工作;它们没有用逗号和空格分隔。

def command(arg):
    arg.insert(-1, 'and')
    value = arg
    for i in range:
        print(value, sep =', ')


spam = []
while True:
    print('Enter the list values:')
    listvalue = input()
    if listvalue == '':
        break
    spam = spam + [listvalue]
command(spam)

3 个答案:

答案 0 :(得分:3)

您必须使用range(stop)or range(start, stop[, step])指定范围值。如果值是列表,也许range(len(value))

您收到异常TypeError: 'type' object is not iterable,因为您引用了类range而不是调用它。

答案 1 :(得分:0)

您需要FOR循环的起点和终点。

例如。这将返回“这是打印”10次。

for i in range(0,9):
    print("This is printed")

答案 2 :(得分:0)

这是执行该操作的代码

def listfunction(stringList):
    strings = ''
    j=0
    for i in range(len(stringList)):
        j=i
        if j == (len(stringList)-1):
            strings = strings + 'and ' + str(stringList[i]) + '.'
        else:
            strings = strings + str(stringList[i]) + ',' + ' '
        #print(strings)   
    return strings