generator-expression - 如何在 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)
解决方案
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 本周中期祝你好运!
推荐阅读
- arrays - 简化 C 中的大量数组声明
- python - 我们是否需要通过来自对象检测模型的所有检测或基于置信度阈值的过滤检测来计算 mAP?
- python - 使用 REST API JSON 响应作为数据在 Python 中构建报告
- python - Python Pillow 降低图像亮度改变背景
- javascript - 在我的 nuxt 网站中嵌入来自 videos.sh 的 iframe
- node.js - 独立的 websocket 客户端
- html - 如何让 HTML 元素跨越同一个类但不被链接
- javascript - 在未填写正确表单时禁用提交 js
- reactjs - 反应快照测试中的模拟状态?
- python - Python:如何使用欧几里得算法从列表中选择心形 X、Y 点