python - 根据步长调整for循环的范围
问题描述
我想请用户确定 for 循环的步长。用户将在输入中写入一个浮点数,例如0.2
or 0.5
,但 Python 在 for 循环中不接受浮点数,因此我们必须将其更改为整数。
for i in range (1, 3.5, 0.5): #This is proposal
print(i)
for i in range (10, 35, 5): #This is the logical term for Python
print(i/10)
如果用户写0.05
循环的范围必须是100 to 350 with step size 5
这意味着我们乘以1
或对于步长我们将它们3.5
乘以。那么我们应该怎么做呢?100
0.5
10
我的意思是当用户写入时,stepseize = 0.00005
我们有十进制数,所以我们必须将和5
乘以前面有零的a,. 如果用户写我们有十进制数,我们必须乘以成1
3.5
1
5
100000
stepseize = 0.0042
4
1
3.5
10000
q = 100... # zeroes are in terms of number of decimals
for i in range (1*(q), 3.5*(q), n*q) : #This is the logical term for Python
print(i/q)
解决方案
您可以编写自己的范围生成器来包装range()
函数但处理浮点数:
def range_floats(start,stop,step):
f = 0
while not step.is_integer():
step *= 10
f += 10
return (i / f for i in range(start*f,stop*f,int(step)))
哪个有效:
>>> for i in range_floats(0, 35, 0.5):
... print(i)
...
0.0
0.5
1.0
.
.
.
33.5
34.0
34.5
推荐阅读
- html - 重新调整立方体的大小
- python - 找不到 Django 404 页面 blog.views.post_detail
- mysql - GROUP_CONCAT 连接一张表而不是全部的结果?
- python - 如何将 facetgrid python 上的 y 轴更改为百分比?
- racket - 某些函数未加载到 repl
- mysql - 如何检查表中的每个字段是另一个表中字段的nt子字符串
- google-apps-script - 谷歌应用脚本newTrigger不为外部文件应用触发器
- c# - UWP后台的TCP/IP连接
- android - 谷歌驱动集成?
- python - 带拉伸的 Tkinter 图像显示