Python函数平方奇数

问题描述 投票:-1回答:2

我收到以下错误“并非在字符串格式化期间转换所有参数”我有以下代码:错误指向代码的这一部分

if num % 2 == 0:
def squareodd(num):
    list = []
    for i in num:
        if i % 2 == 0:
            list.append(i**2)
    return list

squareodd("1,2,3,4,5,6")

预期的输出应该是所有奇数的平方

python python-3.x
2个回答
3
投票
def squareodd(num):
    #lst = () # 'tuple' object has no attribute 'append'
    lst = []
    for i in num:
        # if num % 2 == 0: # you are trying to use the % (modulo) operator on the list instead on item of list 
        if i % 2 == 0:
            lst.append(i**2)
    return lst

print (squareodd([1,2,3,4,5,6]))

1
投票

您需要用逗号分割字符串并将其转换为int对象然后迭代。

例如:

def squareodd(num):
    lst = []
    for i in map(int, num.split(",")):
        if i % 2 == 0:
            lst.append(i**2)
    return lst

print(squareodd("1,2,3,4,5,6"))