简体   繁体   English

枚举 Function Output:

[英]Enumerate Function Output:

Please let me know what is the error here:请让我知道这里的错误是什么:

numbers = [3,11,17,25,28,30,35,32,46,65,97,72,45,22,14,150]
def fizz_buzz(numbers):

    for i,num in enumerate(numbers,start=10):
        if num%3==0:
            numbers[i] = 'fizz'
        if num%5==0:
            numbers[i]= 'buzz'
        if num%3==0 and num%5==0:
            numbers[i]= 'fizzbuzz'
        else:
            continue

    return numbers

print(fizz_buzz(numbers))

Output: Output:

    numbers[i]= 'buzz'
IndexError: list assignment index out of range

You start with index 10你从索引 10 开始

    for i,num in enumerate(numbers,start=10):

So you are accessing the array numbers[16] in the 7th iteration which is out of range.因此,您在第 7 次迭代中访问超出范围的数组numbers[16]

Your array has 16 elements and since array indexing is 0 based, the last element will be numbers[15] and not numbers[16] and your programs is trying to execute numbers[16] so it is getting index out of range error.您的数组有 16 个元素,并且由于数组索引是基于 0 的,因此最后一个元素将是 numbers[15] 而不是 numbers[16],并且您的程序正在尝试执行 numbers[16],因此它会出现索引超出范围错误。

Give a check to your function like below:检查您的 function,如下所示:

numbers = [3,11,17,25,28,30,35,32,46,65,97,72,45,22,14,150]
def fizz_buzz(numbers):

    for i,num in enumerate(numbers,start=10):
        if i < len(numbers):
            if num%3==0:
                numbers[i] = 'fizz'
            if num%5==0:
                numbers[i]= 'buzz'
            if num%3==0 and num%5==0:
                numbers[i]= 'fizzbuzz'
            else:
                continue

    return numbers

print(fizz_buzz(numbers))

To achieve the following output:实现如下output:

[(10,3),(11,11),(12,17),(13,25),(14,28), and so on].

It can be the following:它可以是以下内容:

numbers = [3,11,17,25,28,30,35,32,46,65,97,72,45,22,14,150]

def fizz_buzz(numbers):
    result = []

    for i,num in enumerate(numbers):
        if num%3==0 and num%5==0:
            result.append((i+10, 'fizzbuzz'))
        elif num%3==0:
            result.append((i+10, 'fizz'))
        elif num%5==0:
            result.append((i+10, 'buzz'))
        else:
            result.append((i+10, num))

    return result

print(fizz_buzz(numbers))
# [(10, 'fizz'), (11, 11), (12, 17), (13, 'buzz'), (14, 28), (15, 'fizzbuzz'), (16, 'buzz'), (17, 32), (18, 46), (19, 'buzz'), (20, 97), (21, 'fizz'), (22, 'fizzbuzz'), (23, 22), (24, 14), (25, 'fizzbuzz')]

If you want the answer without fizz/buzz words, do the following:如果您想要没有嘶嘶声/嗡嗡声的答案,请执行以下操作:

numbers = [3,11,17,25,28,30,35,32,46,65,97,72,45,22,14,150]
numbers = [(i+10, num) for i, num in enumerate(numbers)]
print(numbers)
# [(10, 3), (11, 11), (12, 17), (13, 25), (14, 28), (15, 30), (16, 35), (17, 32), (18, 46), (19, 65), (20, 97), (21, 72), (22, 45), (23, 22), (24, 14), (25, 150)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM