定义一个函数,传入一个列表[1,2,3,4,5,6,7],把列表中的奇数返回,返回一个新的列表
参考代码如下:
def fun(lst):
odds=[]
for x in lst:
if x%2!=0:
odds.append(x)
return odds
lst = [1, 2, 3, 4, 5, 6, 7]
print(fun(lst))
使用过滤函数及匿名函数更为简洁一行:
print(list(filter(lambda x:x%2!=0,[1, 2, 3, 4, 5, 6, 7])))
如果回答对你有帮助,请点击我回答的右上方采纳按钮予以采纳~~
l1=[1,2,3,4,5,6,7]
l2=l1[::2]