首页 > 解决方案 > 如何在 python 中使用生成器表达式来创建奇数列表?

问题描述

我将如何将下面的程序更改为产生相同结果的生成器表达式?

print 'this program creates a list of odd numbers in the range of your choice'
start_num=int(input('Enter Starting Number'))
end_num=int(input('Enter ending number'))
my_list=[]
for i in range(start_num,end_num+1):
    if i%2==1:
        my_list.append(i)
print ('odd numbers in the range', my_list)

标签: generator-expression

解决方案


print("this program creates a list of odd numbers in the range of your choice.")

def generator():
     start_num=int(input("enter the starting number:"))
     end_num=int(input("Enter the ending number:"))
     odds=list(i for i in range(start_num,end_num+1)if i%2==1)
     print(odds)


if__name__=='__main__':
     generator()``

PS 本周中期祝你好运!


推荐阅读