|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 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)
求问大佬们,应该怎么基于我这个改对呢?我改来改去总有报错的地方。。
不懂你是不是必须要有什么特定的东西在里面,如果只是单纯的要实现的话,我就给你三个版本的,你按需求来
- # 极简版
- data=[1,2,3,4,5,6,7,8,9]
- print([i ** 2 for i in data if i % 2 != 0])
- # 函数版
- data=[1,2,3,4,5,6,7,8,9]
- def fun(data):
- return [i ** 2 for i in data if i % 2 != 0]
- print(fun(data))
- # input 版
- a = eval(input("输入:"))
- print([int(i)**2 for i in str(a) if int(i) % 2 != 0])
复制代码
|
|