【问题标题】:How to use a generator expression in python to create a list of odd integers?如何在 python 中使用生成器表达式来创建奇数列表?
【发布时间】:2018-12-04 14:29:13
【问题描述】:

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

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


    【解决方案1】:
    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()``
    

    附:本周中期祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      • 2021-11-24
      • 2012-03-16
      • 1970-01-01
      • 2019-04-01
      • 2020-09-06
      相关资源
      最近更新 更多