def frange(start, stop, step=1.0):
''' "range()" like function which accept float type'''
i = start
while i < stop:
yield i
i += step
# Generate one element at a time.
# Preferred when you don't need all generated elements at the same time.
# This will save memory.
for i in frange(1.0, 2.0, 0.5):
print i # Use generated element.
# Generate all elements at once.
# Preferred when generated list ought to be small.
print list(frange(1.0, 10.0, 0.5))
def any_number_range(a,b,s=1):
""" Generate consecutive values list between two numbers with optional step (default=1)."""
if (a == b):
return a
else:
mx = max(a,b)
mn = min(a,b)
result = []
# inclusive upper limit. If not needed, delete '+1' in the line below
while(mn < mx + 1):
# if step is positive we go from min to max
if s > 0:
result.append(mn)
mn += s
# if step is negative we go from max to min
if s < 0:
result.append(mx)
mx += s
return result
>>> list2 = [x*0.5 for x in range(2*x1, 2*x2+1)]
>>> list2
[11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5, 15.0, 15.5, 16.0]
3
最优雅的方法是使用 range 函数,但是如果要重新创建此逻辑,可以执行以下操作:
def custom_range(*args):
s = slice(*args)
start, stop, step = s.start, s.stop, s.step
if 0 == step:
raise ValueError("range() arg 3 must not be zero")
i = start
while i < stop if step > 0 else i > stop:
yield i
i += step
>>> [x for x in custom_range(10, 3, -1)]
这会产生输出:
[10, 9, 8, 7, 6, 5, 4]
正如之前由@Jared所表达的,最好的方法是使用 range 或 numpy.arrange 然而我发现有趣的代码可以共享 .
8 回答
尝试:
这是Python 2.x中的列表,其行为大多类似于Python 3.x中的列表 . 如果您正在运行Python 3并且需要可以修改的列表,请使用:
如果你正在寻找适用于float类型的函数的范围,那么这里是一个非常好的article .
输出:
在python中使用list comprehension . 由于您也希望在列表中使用16 ..使用x2 1.范围功能排除函数中的上限 .
假设你想要一个介于x到y之间的范围
使用列表获得3.x支持
上面的每个答案都假定范围仅为正数 . 这是返回连续数列表的解决方案,其中参数可以是任意(正或负),可以设置可选步长值(默认值= 1) .
例如,标准命令
list(range(1,-3))
返回空列表[]
,而此函数将返回[-3,-2,-1,0,1]
Updated :现在步骤可能是否定的 . 感谢@Michael的评论 .
你似乎在寻找range():
要按
0.5
而不是1
递增,请说:最优雅的方法是使用
range
函数,但是如果要重新创建此逻辑,可以执行以下操作:这会产生输出:
正如之前由@Jared所表达的,最好的方法是使用
range
或numpy.arrange
然而我发现有趣的代码可以共享 .使用range . 在Python 2.x中它返回一个列表,所以你需要的只是,
在Python 3.x中它是一个迭代器,所以你需要将它转换为一个列表,
Note :第二个数字是独占的,所以这里需要
16+1
=17
编辑:
要回答有关按
0.5
递增的问题,最简单的选择可能是使用numpy的arange
,