简体   繁体   中英

How would I define a function in python to append a word to an integer in a list depending on the integer multiple?

I'm trying to define a function in python that would take any list of integers. If the integer is a multiple of 3 and 5, it will an in the variable a to the list. If the integer is a multiple of only 3, it will add in the variable b to the list. If the integer is a multiple of only 5, it will add in variable c to the list.

How do you reference each item in a list within an iterative function?

Here's what I have so far. Thanks

intList = [15, 30, 40]

def function(intList):
    a = 'Fizz'
    b = 'Buzz'
    c = a + b
for x in intList:
    if x in intList % 5 == 0 and x in intList % 3 == 0:
        intList.append(c)
    elif x in intList % 3 == 0:
        intList.append(a)
    elif x in intList % 5 == 0:
        intList.append(b)



print(function(intList))

Response

Traceback (most recent call last):
  File "python", line 18, in <module>
  File "python", line 6, in function
NameError: name 'x' is not defined

The response I'm looking to get is [15, 'FizzBuzz', 30, 'FizzBuzz', 40, 'Buzz']

To stay close to your code, here is what you can do :

def fizz_buzz(intList):
    a = 'Fizz'
    b = 'Buzz'
    c = a + b

    res = []

    for x in intList:
        if (x % 5 == 0) and (x % 3 == 0):
            res = res + [x,c]
        elif x % 3 == 0:
            res = res + [x,a]
        elif x % 5 == 0:
            res = res + [x,b]

    return res

list = [1, 15, 30, 40] 

print(fizz_buzz(list))

>>> [15, 'FizzBuzz', 30, 'FizzBuzz', 40, 'Buzz']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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