我遇到以下错误 “并非在字符串格式化期间转换了所有参数” 我有以下代码: 错误指向代码的这一部分
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")
预期输出应该是所有奇数的平方
答案 0 :(得分: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 :(得分: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"))