stanley-cheung 发表于 2020-10-26 02:02:32

关于函数的问题

本帖最后由 stanley-cheung 于 2020-10-26 02:19 编辑

题目是
Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. >Suppose the following input is supplied to the program:举例,
1,2,3,4,5,6,7,8,9
Then, the output should be:
1,9,25,49,81

我写的:
data=input().split(',')
data=[]


def check():
    for i in data:
   if i%2!=0:
       b=i**2
       return b


c=filter(check,data)
print(c)

求问大佬们,应该怎么基于我这个改对呢?我改来改去总有报错的地方。。

kogawananari 发表于 2020-10-26 02:12:13

filter 函数要求返回bool
你这个功能需要map和filter都用
或者列表生成式

data=
c1=filter(lambda i:i%2,data)
c2=map(lambda i:i*i,c1)
print(list(c2))

print()

jtxs0000 发表于 2020-10-26 09:31:26

不懂你是不是必须要有什么特定的东西在里面,如果只是单纯的要实现的话,我就给你三个版本的,你按需求来

# 极简版
data=
print()

# 函数版
data=
def fun(data):
    return

print(fun(data))

# input 版
a = eval(input("输入:"))
print()

冬雪雪冬 发表于 2020-10-26 10:25:26

temp = input().split(',')
list1 = list(map(int, temp))
list2 = ** 2 for i in range(0, len(list1), 2)]
print(*list2,sep = ',')
页: [1]
查看完整版本: 关于函数的问题