如何使用十进制范围()步骤值?

时间:2021-09-29 17:07:42

Is there a way to step between 0 and 1 by 0.1?

有没有一种方法可以在0和1之间移动0.1?

I thought I could do it like the following, but it failed:

我想我可以这样做,但是失败了:

for i in range(0, 1, 0.1):    print i

Instead, it says that the step argument cannot be zero, which I did not expect.

相反,它说阶跃参数不能是零,这是我没有想到的。

31 个解决方案

#1


591  

You can also use the NumPy library (which isn't part of standard library but is relatively easy to obtain) which has the arange function:

您还可以使用NumPy库(它不是标准库的一部分,但相对容易获得),它具有arange函数:

>>> import numpy as np>>> np.arange(0.0, 1.0, 0.1)array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])

as well as the linspace function which lets you have control over what happens at the endpoint (non-trivial for floating point numbers when things won't always divide into the correct number of "slices"):

以及linspace函数,它可以让你控制端点上发生的事情(对于浮点数来说,当事情不总是被划分成正确的“切片”数目时,这一点很重要):

>>> np.linspace(0,1,11)array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ])>>> np.linspace(0,1,10,endpoint=False)array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])

#2


150  

Python's range() can only do integers, not floating point. In your specific case, you can use a list comprehension instead:

Python的range()只能处理整数,不能处理浮点数。在你的具体情况下,你可以使用列表理解代替:

[x * 0.1 for x in range(0, 10)]

(Replace the call to range with that expression.)

(用该表达式替换对range的调用。)

For the more general case, you may want to write a custom function or generator.

对于更一般的情况,您可能需要编写自定义函数或生成器。

#3


139  

Building on 'xrange([start], stop[, step])', you can define a generator that accepts and produces any type you choose (stick to types supporting + and <):

基于“xrange([start]、stop[、step])”,您可以定义一个生成器,它接受并生成您选择的任何类型(坚持支持+和 <的类型):< p>

>>> def drange(start, stop, step):...     r = start...     while r < stop:...         yield r...         r += step...         >>> i0=drange(0.0, 1.0, 0.1)>>> ["%g" % x for x in i0]['0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1']>>> 

#4


30  

Increase the magnitude of i for the loop and then reduce it when you need it.

增加循环的i的大小,然后在需要的时候减少它。

for i * 100 in range(0, 100, 10):    print i / 100.0

EDIT: I honestly cannot remember why I thought that would work syntactically

编辑:老实说,我不记得为什么我认为它在语法上行得通

for i in range(0, 11, 1):    print i / 10.0

That should have the desired output.

它应该有理想的输出。

#5


20  

scipy has a built in function arange which generalizes Python's range() constructor to satisfy your requirement of float handling.

scipy有一个内置的函数arange,它将Python的range()构造函数一般化,以满足您对浮点处理的要求。

from scipy import arange

从scipy进口论坛

#6


16  

Similar to R's seq function, this one returns a sequence in any order given the correct step value. The last value is equal to the stop value.

类似于R的seq函数,这个函数返回一个给定正确步长值的序列。最后一个值等于停止值。

def seq(start, stop, step=1):    n = int(round((stop - start)/float(step)))    if n > 1:        return([start + step*i for i in range(n+1)])    elif n == 1:        return([start])    else:        return([])

Results

seq(1, 5, 0.5)

[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]

[1.0、1.5、2.0、2.5、3.0、3.5、4.0、4.5、5.0]

seq(10, 0, -1)

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

[10、9、8、7、6、5、4、3、2、1、0]

seq(10, 0, -2)

[10, 8, 6, 4, 2, 0]

[10,8,6,4,2,0]

seq(1, 1)

[ 1 ]

[1]

#7


15  

NumPy is a bit overkill, I think.

我觉得麻木有点过头了。

[p/10 for p in range(0, 10)][0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

Generally speaking, to do a step-by-1/x up to y you would do

一般来说,做1/x到y的步长

x=100y=2[p/x for p in range(0, int(x*y))][0.0, 0.01, 0.02, 0.03, ..., 1.97, 1.98, 1.99]

(1/x produced less rounding noise when I tested).

(1/x测试时产生的舍入噪声较少)。

#8


10  

The range() built-in function returns a sequence of integer values, I'm afraid, so you can't use it to do a decimal step.

range()内置函数返回一个整数值序列,恐怕您不能使用它来执行十进制步骤。

I'd say just use a while loop:

我想说用while循环:

i = 0.0while i <= 1.0:    print i    i += 0.1

If you're curious, Python is converting your 0.1 to 0, which is why it's telling you the argument can't be zero.

如果您好奇,Python正在将0.1转换为0,这就是为什么它告诉您参数不能为0。

#9


9  

import numpy as npfor i in np.arange(0, 1, 0.1):     print i 

#10


8  

Here's a solution using itertools:

这里有一个使用迭代工具的解决方案:

import itertoolsdef seq(start, end, step):    assert(step != 0)    sample_count = abs(end - start) / step    return itertools.islice(itertools.count(start, step), sample_count)

Usage Example:

使用的例子:

for i in seq(0, 1, 0.1):    print i

Output:

输出:

00.10.20.30.40.50.60.70.80.9

#11


7  

[x * 0.1 for x in range(0, 10)] 

in Python 2.7x gives you the result of:

在Python 2.7x中给出的结果是:

[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]

[0.0,0.1,0.2,0.30000000000000004,0.4,0.5,0.600000000001,0.700000000001,0.8,0.9]

but if you use:

但是如果你使用:

[ round(x * 0.1, 1) for x in range(0, 10)]

gives you the desired:

给你所需的:

[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

(0.0,0.1,0.2,0.0,0.1,0.5,0.6,0.7,0.8,0.9)

#12


5  

And if you do this often, you might want to save the generated list r

如果你经常这样做,你可能想要保存生成的列表r

r=map(lambda x: x/10.0,range(0,10))for i in r:    print i

#13


4  

My versions use the original range function to create multiplicative indices for the shift. This allows same syntax to the original range function.I have made two versions, one using float, and one using Decimal, because I found that in some cases I wanted to avoid the roundoff drift introduced by the floating point arithmetic.

我的版本使用原始的范围函数来创建移位的乘法索引。这允许对原始范围函数使用相同的语法。我制作了两个版本,一个使用浮点数,另一个使用十进制数,因为我发现在某些情况下,我想避免浮点算法引入的舍入漂移。

It is consistent with empty set results as in range/xrange.

它与在range/xrange中的空集结果一致。

Passing only a single numeric value to either function will return the standard range output to the integer ceiling value of the input parameter (so if you gave it 5.5, it would return range(6).)

只向任何一个函数传递一个数值将返回标准范围输出到输入参数的整数上限值(所以如果您给它5.5,它将返回范围(6))。

Edit: the code below is now available as package on pypi: Franges

编辑:下面的代码现在可以作为pypi: Franges的软件包使用

## frange.pyfrom math import ceil# find best range function available to version (2.7.x / 3.x.x)try:    _xrange = xrangeexcept NameError:    _xrange = rangedef frange(start, stop = None, step = 1):    """frange generates a set of floating point values over the     range [start, stop) with step size step    frange([start,] stop [, step ])"""    if stop is None:        for x in _xrange(int(ceil(start))):            yield x    else:        # create a generator expression for the index values        indices = (i for i in _xrange(0, int((stop-start)/step)))          # yield results        for i in indices:            yield start + step*i## drange.pyimport decimalfrom math import ceil# find best range function available to version (2.7.x / 3.x.x)try:    _xrange = xrangeexcept NameError:    _xrange = rangedef drange(start, stop = None, step = 1, precision = None):    """drange generates a set of Decimal values over the    range [start, stop) with step size step    drange([start,] stop, [step [,precision]])"""    if stop is None:        for x in _xrange(int(ceil(start))):            yield x    else:        # find precision        if precision is not None:            decimal.getcontext().prec = precision        # convert values to decimals        start = decimal.Decimal(start)        stop = decimal.Decimal(stop)        step = decimal.Decimal(step)        # create a generator expression for the index values        indices = (            i for i in _xrange(                0,                 ((stop-start)/step).to_integral_value()            )        )          # yield results        for i in indices:            yield float(start + step*i)## testranges.pyimport frangeimport drangelist(frange.frange(0, 2, 0.5)) # [0.0, 0.5, 1.0, 1.5]list(drange.drange(0, 2, 0.5, precision = 6)) # [0.0, 0.5, 1.0, 1.5]list(frange.frange(3)) # [0, 1, 2]list(frange.frange(3.5)) # [0, 1, 2, 3]list(frange.frange(0,10, -1)) # []

#14


4  

This is my solution to get ranges with float steps.
Using this function it's not necessary to import numpy, nor install it.
I'm pretty sure that it could be improved and optimized. Feel free to do it and post it here.

这是我使用浮动步骤获得范围的解决方案。使用这个函数,不需要导入numpy,也不需要安装它。我很确定它可以得到改进和优化。你可以在这里发布。

from __future__ import divisionfrom math import logdef xfrange(start, stop, step):    old_start = start #backup this value    digits = int(round(log(10000, 10)))+1 #get number of digits    magnitude = 10**digits    stop = int(magnitude * stop) #convert from     step = int(magnitude * step) #0.1 to 10 (e.g.)    if start == 0:        start = 10**(digits-1)    else:        start = 10**(digits)*start    data = []   #create array    #calc number of iterations    end_loop = int((stop-start)//step)    if old_start == 0:        end_loop += 1    acc = start    for i in xrange(0, end_loop):        data.append(acc/magnitude)        acc += step    return dataprint xfrange(1, 2.1, 0.1)print xfrange(0, 1.1, 0.1)print xfrange(-1, 0.1, 0.1)

The output is:

的输出是:

[1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0][0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1][-1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.0]

#15


2  

You can use this function:

你可以使用这个功能:

def frange(start,end,step):    return map(lambda x: x*step, range(int(start*1./step),int(end*1./step)))

#16


2  

For completeness of boutique, a functional solution:

为了精品店的完整性,一种功能解决方案:

def frange(a,b,s):  return [] if s > 0 and a > b or s < 0 and a < b or s==0 else [a]+frange(a+s,b,s)

#17


2  

It can be done using Numpy library. arange() function allows steps in float. But, it returns a numpy array which can be converted to list using tolist() for our convenience.

它可以使用Numpy库完成。函数的作用是:允许浮动的步骤。但是,它返回一个numpy数组,为了方便,可以使用tolist()将其转换为list。

for i in np.arange(0, 1, 0.1).tolist():   print i

#18


2  

My answer is similar to others using map(), without need of NumPy, and without using lambda (though you could). To get a list of float values from 0.0 to t_max in steps of dt:

我的回答与使用map()的其他人类似,不需要NumPy,也不使用lambda(尽管您可以)。以dt为步骤,从0.0到t_max的浮点值列表:

def xdt(n):    return dt*float(n)tlist  = map(xdt, range(int(t_max/dt)+1))

#19


2  

more_itertools is a third-party library that implements a numeric_range tool:

more_itertools是一个实现numeric_range工具的第三方库:

import more_itertools as mitfor x in mit.numeric_range(0, 1, 0.1):    print("{:.1f}".format(x))

Output

输出

0.00.10.20.30.40.50.60.70.80.9

This tool also works for Decimal and Fraction.

这个工具也适用于小数和小数。

#20


1  

Add auto-correction for the possibility of an incorrect sign on step:

增加自动更正的可能性不正确的标志在步骤:

def frange(start,step,stop):    step *= 2*((stop>start)^(step<0))-1    return [start+i*step for i in range(int((stop-start)/step))]

#21


1  

My solution:

我的解决方案:

def seq(start, stop, step=1, digit=0):    x = float(start)    v = []    while x <= stop:        v.append(round(x,digit))        x += step    return v

#22


1  

The trick to avoid round-off problem is to use a separate number to move through the range, that starts and half the step ahead of start.

避免“四舍五入”问题的诀窍是使用一个单独的数字在开始和开始前的一半的范围内移动。

# floating point rangedef frange(a, b, stp=1.0):  i = a+stp/2.0  while i<b:    yield a    a += stp    i += stp

Alternatively, numpy.arange can be used.

另外,numpy。可以使用论坛。

#23


1  

Best Solution: no rounding error
_________________________________________________________________________________

最好的解决方案:不舍入误差_________________________________________________________________________________

>>> step = .1>>> N = 10     # number of data points>>> [ x / pow(step, -1) for x in range(0, N + 1) ][0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

_________________________________________________________________________________

Or, for a set range instead of set data points (e.g. continuous function), use:

_________________________________________________________________________________或者一组范围而不是设置数据点(如连续函数),使用:

>>> step = .1>>> rnge = 1     # NOTE range = 1, i.e. span of data points>>> N = int(rnge / step>>> [ x / pow(step,-1) for x in range(0, N + 1) ][0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

To implement a function: replace x / pow(step, -1) with f( x / pow(step, -1) ), and define f.
For example:

实现一个函数:将x / pow(step, -1)替换为f(x / pow(step, -1)),定义f。

>>> import math>>> def f(x):        return math.sin(x)>>> step = .1>>> rnge = 1     # NOTE range = 1, i.e. span of data points>>> N = int(rnge / step)>>> [ f( x / pow(step,-1) ) for x in range(0, N + 1) ][0.0, 0.09983341664682815, 0.19866933079506122, 0.29552020666133955, 0.3894183423086505,  0.479425538604203, 0.5646424733950354, 0.644217687237691, 0.7173560908995228, 0.7833269096274834, 0.8414709848078965]

#24


1  

Suprised no-one has yet mentioned the recommended solution in the Python 3 docs:

出乎意料的是,还没有人提到Python 3文档中推荐的解决方案:

See also:

参见:

  • The linspace recipe shows how to implement a lazy version of range that suitable for floating point applications.
  • linspace食谱展示了如何实现一个适用于浮点应用程序的懒惰版本。

Once defined, the recipe is easy to use and does not require numpy or any other external libraries, but functions like numpy.linspace(). Note that rather than a step argument, the third num argument specifies the number of desired values, for example:

一旦定义,该菜谱就很容易使用,不需要numpy或任何其他外部库,而是使用numpy.linspace()之类的函数。注意,与step参数不同,第三个num参数指定所需值的数量,例如:

print(linspace(0, 10, 5))# linspace(0, 10, 5)print(list(linspace(0, 10, 5)))# [0.0, 2.5, 5.0, 7.5, 10]

I quote a modified version of the full Python 3 recipe from Andrew Barnert below:

我引用了来自Andrew Barnert的完整的Python 3食谱的修改版本:

import collections.abcimport numbersclass linspace(collections.abc.Sequence):    """linspace(start, stop, num) -> linspace object    Return a virtual sequence of num numbers from start to stop (inclusive).    If you need a half-open range, use linspace(start, stop, num+1)[:-1].    """    def __init__(self, start, stop, num):        if not isinstance(num, numbers.Integral) or num <= 1:            raise ValueError('num must be an integer > 1')        self.start, self.stop, self.num = start, stop, num        self.step = (stop-start)/(num-1)    def __len__(self):        return self.num    def __getitem__(self, i):        if isinstance(i, slice):            return [self[x] for x in range(*i.indices(len(self)))]        if i < 0:            i = self.num + i        if i >= self.num:            raise IndexError('linspace object index out of range')        if i == self.num-1:            return self.stop        return self.start + i*self.step    def __repr__(self):        return '{}({}, {}, {})'.format(type(self).__name__,                                       self.start, self.stop, self.num)    def __eq__(self, other):        if not isinstance(other, linspace):            return False        return ((self.start, self.stop, self.num) ==                (other.start, other.stop, other.num))    def __ne__(self, other):        return not self==other    def __hash__(self):        return hash((type(self), self.start, self.stop, self.num))

#25


0  

Here is my solution which works fine with float_range(-1, 0, 0.01) and works without floating point representation errors. It is not very fast, but works fine:

下面是我的解决方案,它适用于float_range(- 1,0,0.01),并且没有浮点表示错误。它不是很快,但效果很好:

from decimal import Decimaldef get_multiplier(_from, _to, step):    digits = []    for number in [_from, _to, step]:        pre = Decimal(str(number)) % 1        digit = len(str(pre)) - 2        digits.append(digit)    max_digits = max(digits)    return float(10 ** (max_digits))def float_range(_from, _to, step, include=False):    """Generates a range list of floating point values over the Range [start, stop]       with step size step       include=True - allows to include right value to if possible       !! Works fine with floating point representation !!    """    mult = get_multiplier(_from, _to, step)    # print mult    int_from = int(round(_from * mult))    int_to = int(round(_to * mult))    int_step = int(round(step * mult))    # print int_from,int_to,int_step    if include:        result = range(int_from, int_to + int_step, int_step)        result = [r for r in result if r <= int_to]    else:        result = range(int_from, int_to, int_step)    # print result    float_result = [r / mult for r in result]    return float_resultprint float_range(-1, 0, 0.01,include=False)assert float_range(1.01, 2.06, 5.05 % 1, True) ==\[1.01, 1.06, 1.11, 1.16, 1.21, 1.26, 1.31, 1.36, 1.41, 1.46, 1.51, 1.56, 1.61, 1.66, 1.71, 1.76, 1.81, 1.86, 1.91, 1.96, 2.01, 2.06]assert float_range(1.01, 2.06, 5.05 % 1, False)==\[1.01, 1.06, 1.11, 1.16, 1.21, 1.26, 1.31, 1.36, 1.41, 1.46, 1.51, 1.56, 1.61, 1.66, 1.71, 1.76, 1.81, 1.86, 1.91, 1.96, 2.01]

#26


0  

I am only a beginner, but I had the same problem, when simulating some calculations. Here is how I attempted to work this out, which seems to be working with decimal steps.

我只是个初学者,但在模拟一些计算时,我遇到了同样的问题。下面是我如何计算的,它似乎是用十进制的步骤。

I am also quite lazy and so I found it hard to write my own range function.

我也很懒,所以我发现很难写出我自己的range函数。

Basically what I did is changed my xrange(0.0, 1.0, 0.01) to xrange(0, 100, 1) and used the division by 100.0 inside the loop.I was also concerned, if there will be rounding mistakes. So I decided to test, whether there are any. Now I heard, that if for example 0.01 from a calculation isn't exactly the float 0.01 comparing them should return False (if I am wrong, please let me know).

基本上,我所做的就是将xrange(0.0, 1.0, 0.01)更改为xrange(0,100, 1)并在循环中使用100.0进行除法。我也担心是否会出现四舍五入的错误。所以我决定测试,是否有。现在我听说,如果从计算中得到的0.01不是浮点数0.01,那么它们应该返回False(如果我错了,请告诉我)。

So I decided to test if my solution will work for my range by running a short test:

所以我决定通过一个简短的测试来测试我的解决方案是否适用于我的范围:

for d100 in xrange(0, 100, 1):    d = d100 / 100.0    fl = float("0.00"[:4 - len(str(d100))] + str(d100))    print d, "=", fl , d == fl

And it printed True for each.

每个都打印出来了。

Now, if I'm getting it totally wrong, please let me know.

如果我完全搞错了,请告诉我。

#27


0  

This one liner will not clutter your code. The sign of the step parameter is important.

这一行代码不会打乱你的代码。步骤参数的符号很重要。

def frange(start, stop, step):    return [x*step+start for x in range(0,round(abs((stop-start)/step)+0.5001),        int((stop-start)/step<0)*-2+1)]

#28


0  

frange(start, stop, precision)

纤毛刷(启动、停止、精度)

def frange(a,b,i):    p = 10**i    sr = a*p    er = (b*p) + 1    p = float(p)    return map(lambda x: x/p, xrange(sr,er))In >frange(-1,1,1)Out>[-1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

#29


0  

start and stop are inclusive rather than one or the other (usually stop is excluded) and without imports, and using generators

启动和停止是兼容的,而不是一个或另一个(通常停止被排除),没有导入,并使用生成器。

def rangef(start, stop, step, fround=5):    """    Yields sequence of numbers from start (inclusive) to stop (inclusive)    by step (increment) with rounding set to n digits.    :param start: start of sequence    :param stop: end of sequence    :param step: int or float increment (e.g. 1 or 0.001)    :param fround: float rounding, n decimal places    :return:    """    try:        i = 0        while stop >= start and step > 0:            if i==0:                yield start            elif start >= stop:                yield stop            elif start < stop:                if start == 0:                    yield 0                if start != 0:                    yield start            i += 1            start += step            start = round(start, fround)        else:            pass    except TypeError as e:        yield "type-error({})".format(e)    else:        pass# passingprint(list(rangef(-100.0,10.0,1)))print(list(rangef(-100,0,0.5)))print(list(rangef(-1,1,0.2)))print(list(rangef(-1,1,0.1)))print(list(rangef(-1,1,0.05)))print(list(rangef(-1,1,0.02)))print(list(rangef(-1,1,0.01)))print(list(rangef(-1,1,0.005)))# failing: type-error:print(list(rangef("1","10","1")))print(list(rangef(1,10,"1")))

Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)]

Python 3.6.2 (v3.6.2:5fd33b5, 2017年7月8日,04:57:36)[MSC v.]1900 64位(AMD64))

#30


0  

To counter the float precision issues, you could use the Decimal module.

为了解决浮点精度问题,可以使用Decimal模块。

This demands an extra effort of converting to Decimal from int or float while writing the code, but you can instead pass str and modify the function if that sort of convenience is indeed necessary.

这需要在编写代码时从int或float转换为Decimal,但是如果确实需要这种方便,您可以通过str并修改函数。

from decimal import Decimalfrom decimal import Decimal as Ddef decimal_range(*args):    zero, one = Decimal('0'), Decimal('1')    if len(args) == 1:        start, stop, step = zero, args[0], one    elif len(args) == 2:        start, stop, step = args + (one,)    elif len(args) == 3:        start, stop, step = args    else:        raise ValueError('Expected 1 or 2 arguments, got %s' % len(args))    if not all([type(arg) == Decimal for arg in (start, stop, step)]):        raise ValueError('Arguments must be passed as <type: Decimal>')    # neglect bad cases    if (start == stop) or (start > stop and step >= zero) or \                          (start < stop and step <= zero):        return []    current = start    while abs(current) < abs(stop):        yield current        current += step

Sample outputs -

样本输出-

list(decimal_range(D('2')))# [Decimal('0'), Decimal('1')]list(decimal_range(D('2'), D('4.5')))# [Decimal('2'), Decimal('3'), Decimal('4')]list(decimal_range(D('2'), D('4.5'), D('0.5')))# [Decimal('2'), Decimal('2.5'), Decimal('3.0'), Decimal('3.5'), Decimal('4.0')]list(decimal_range(D('2'), D('4.5'), D('-0.5')))# []list(decimal_range(D('2'), D('-4.5'), D('-0.5')))# [Decimal('2'),#  Decimal('1.5'),#  Decimal('1.0'),#  Decimal('0.5'),#  Decimal('0.0'),#  Decimal('-0.5'),#  Decimal('-1.0'),#  Decimal('-1.5'),#  Decimal('-2.0'),#  Decimal('-2.5'),#  Decimal('-3.0'),#  Decimal('-3.5'),#  Decimal('-4.0')]

#1


591  

You can also use the NumPy library (which isn't part of standard library but is relatively easy to obtain) which has the arange function:

您还可以使用NumPy库(它不是标准库的一部分,但相对容易获得),它具有arange函数:

>>> import numpy as np>>> np.arange(0.0, 1.0, 0.1)array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])

as well as the linspace function which lets you have control over what happens at the endpoint (non-trivial for floating point numbers when things won't always divide into the correct number of "slices"):

以及linspace函数,它可以让你控制端点上发生的事情(对于浮点数来说,当事情不总是被划分成正确的“切片”数目时,这一点很重要):

>>> np.linspace(0,1,11)array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ])>>> np.linspace(0,1,10,endpoint=False)array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])

#2


150  

Python's range() can only do integers, not floating point. In your specific case, you can use a list comprehension instead:

Python的range()只能处理整数,不能处理浮点数。在你的具体情况下,你可以使用列表理解代替:

[x * 0.1 for x in range(0, 10)]

(Replace the call to range with that expression.)

(用该表达式替换对range的调用。)

For the more general case, you may want to write a custom function or generator.

对于更一般的情况,您可能需要编写自定义函数或生成器。

#3


139  

Building on 'xrange([start], stop[, step])', you can define a generator that accepts and produces any type you choose (stick to types supporting + and <):

基于“xrange([start]、stop[、step])”,您可以定义一个生成器,它接受并生成您选择的任何类型(坚持支持+和 <的类型):< p>

>>> def drange(start, stop, step):...     r = start...     while r < stop:...         yield r...         r += step...         >>> i0=drange(0.0, 1.0, 0.1)>>> ["%g" % x for x in i0]['0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1']>>> 

#4


30  

Increase the magnitude of i for the loop and then reduce it when you need it.

增加循环的i的大小,然后在需要的时候减少它。

for i * 100 in range(0, 100, 10):    print i / 100.0

EDIT: I honestly cannot remember why I thought that would work syntactically

编辑:老实说,我不记得为什么我认为它在语法上行得通

for i in range(0, 11, 1):    print i / 10.0

That should have the desired output.

它应该有理想的输出。

#5


20  

scipy has a built in function arange which generalizes Python's range() constructor to satisfy your requirement of float handling.

scipy有一个内置的函数arange,它将Python的range()构造函数一般化,以满足您对浮点处理的要求。

from scipy import arange

从scipy进口论坛

#6


16  

Similar to R's seq function, this one returns a sequence in any order given the correct step value. The last value is equal to the stop value.

类似于R的seq函数,这个函数返回一个给定正确步长值的序列。最后一个值等于停止值。

def seq(start, stop, step=1):    n = int(round((stop - start)/float(step)))    if n > 1:        return([start + step*i for i in range(n+1)])    elif n == 1:        return([start])    else:        return([])

Results

seq(1, 5, 0.5)

[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]

[1.0、1.5、2.0、2.5、3.0、3.5、4.0、4.5、5.0]

seq(10, 0, -1)

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

[10、9、8、7、6、5、4、3、2、1、0]

seq(10, 0, -2)

[10, 8, 6, 4, 2, 0]

[10,8,6,4,2,0]

seq(1, 1)

[ 1 ]

[1]

#7


15  

NumPy is a bit overkill, I think.

我觉得麻木有点过头了。

[p/10 for p in range(0, 10)][0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

Generally speaking, to do a step-by-1/x up to y you would do

一般来说,做1/x到y的步长

x=100y=2[p/x for p in range(0, int(x*y))][0.0, 0.01, 0.02, 0.03, ..., 1.97, 1.98, 1.99]

(1/x produced less rounding noise when I tested).

(1/x测试时产生的舍入噪声较少)。

#8


10  

The range() built-in function returns a sequence of integer values, I'm afraid, so you can't use it to do a decimal step.

range()内置函数返回一个整数值序列,恐怕您不能使用它来执行十进制步骤。

I'd say just use a while loop:

我想说用while循环:

i = 0.0while i <= 1.0:    print i    i += 0.1

If you're curious, Python is converting your 0.1 to 0, which is why it's telling you the argument can't be zero.

如果您好奇,Python正在将0.1转换为0,这就是为什么它告诉您参数不能为0。

#9


9  

import numpy as npfor i in np.arange(0, 1, 0.1):     print i 

#10


8  

Here's a solution using itertools:

这里有一个使用迭代工具的解决方案:

import itertoolsdef seq(start, end, step):    assert(step != 0)    sample_count = abs(end - start) / step    return itertools.islice(itertools.count(start, step), sample_count)

Usage Example:

使用的例子:

for i in seq(0, 1, 0.1):    print i

Output:

输出:

00.10.20.30.40.50.60.70.80.9

#11


7  

[x * 0.1 for x in range(0, 10)] 

in Python 2.7x gives you the result of:

在Python 2.7x中给出的结果是:

[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]

[0.0,0.1,0.2,0.30000000000000004,0.4,0.5,0.600000000001,0.700000000001,0.8,0.9]

but if you use:

但是如果你使用:

[ round(x * 0.1, 1) for x in range(0, 10)]

gives you the desired:

给你所需的:

[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

(0.0,0.1,0.2,0.0,0.1,0.5,0.6,0.7,0.8,0.9)

#12


5  

And if you do this often, you might want to save the generated list r

如果你经常这样做,你可能想要保存生成的列表r

r=map(lambda x: x/10.0,range(0,10))for i in r:    print i

#13


4  

My versions use the original range function to create multiplicative indices for the shift. This allows same syntax to the original range function.I have made two versions, one using float, and one using Decimal, because I found that in some cases I wanted to avoid the roundoff drift introduced by the floating point arithmetic.

我的版本使用原始的范围函数来创建移位的乘法索引。这允许对原始范围函数使用相同的语法。我制作了两个版本,一个使用浮点数,另一个使用十进制数,因为我发现在某些情况下,我想避免浮点算法引入的舍入漂移。

It is consistent with empty set results as in range/xrange.

它与在range/xrange中的空集结果一致。

Passing only a single numeric value to either function will return the standard range output to the integer ceiling value of the input parameter (so if you gave it 5.5, it would return range(6).)

只向任何一个函数传递一个数值将返回标准范围输出到输入参数的整数上限值(所以如果您给它5.5,它将返回范围(6))。

Edit: the code below is now available as package on pypi: Franges

编辑:下面的代码现在可以作为pypi: Franges的软件包使用

## frange.pyfrom math import ceil# find best range function available to version (2.7.x / 3.x.x)try:    _xrange = xrangeexcept NameError:    _xrange = rangedef frange(start, stop = None, step = 1):    """frange generates a set of floating point values over the     range [start, stop) with step size step    frange([start,] stop [, step ])"""    if stop is None:        for x in _xrange(int(ceil(start))):            yield x    else:        # create a generator expression for the index values        indices = (i for i in _xrange(0, int((stop-start)/step)))          # yield results        for i in indices:            yield start + step*i## drange.pyimport decimalfrom math import ceil# find best range function available to version (2.7.x / 3.x.x)try:    _xrange = xrangeexcept NameError:    _xrange = rangedef drange(start, stop = None, step = 1, precision = None):    """drange generates a set of Decimal values over the    range [start, stop) with step size step    drange([start,] stop, [step [,precision]])"""    if stop is None:        for x in _xrange(int(ceil(start))):            yield x    else:        # find precision        if precision is not None:            decimal.getcontext().prec = precision        # convert values to decimals        start = decimal.Decimal(start)        stop = decimal.Decimal(stop)        step = decimal.Decimal(step)        # create a generator expression for the index values        indices = (            i for i in _xrange(                0,                 ((stop-start)/step).to_integral_value()            )        )          # yield results        for i in indices:            yield float(start + step*i)## testranges.pyimport frangeimport drangelist(frange.frange(0, 2, 0.5)) # [0.0, 0.5, 1.0, 1.5]list(drange.drange(0, 2, 0.5, precision = 6)) # [0.0, 0.5, 1.0, 1.5]list(frange.frange(3)) # [0, 1, 2]list(frange.frange(3.5)) # [0, 1, 2, 3]list(frange.frange(0,10, -1)) # []

#14


4  

This is my solution to get ranges with float steps.
Using this function it's not necessary to import numpy, nor install it.
I'm pretty sure that it could be improved and optimized. Feel free to do it and post it here.

这是我使用浮动步骤获得范围的解决方案。使用这个函数,不需要导入numpy,也不需要安装它。我很确定它可以得到改进和优化。你可以在这里发布。

from __future__ import divisionfrom math import logdef xfrange(start, stop, step):    old_start = start #backup this value    digits = int(round(log(10000, 10)))+1 #get number of digits    magnitude = 10**digits    stop = int(magnitude * stop) #convert from     step = int(magnitude * step) #0.1 to 10 (e.g.)    if start == 0:        start = 10**(digits-1)    else:        start = 10**(digits)*start    data = []   #create array    #calc number of iterations    end_loop = int((stop-start)//step)    if old_start == 0:        end_loop += 1    acc = start    for i in xrange(0, end_loop):        data.append(acc/magnitude)        acc += step    return dataprint xfrange(1, 2.1, 0.1)print xfrange(0, 1.1, 0.1)print xfrange(-1, 0.1, 0.1)

The output is:

的输出是:

[1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0][0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1][-1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.0]

#15


2  

You can use this function:

你可以使用这个功能:

def frange(start,end,step):    return map(lambda x: x*step, range(int(start*1./step),int(end*1./step)))

#16


2  

For completeness of boutique, a functional solution:

为了精品店的完整性,一种功能解决方案:

def frange(a,b,s):  return [] if s > 0 and a > b or s < 0 and a < b or s==0 else [a]+frange(a+s,b,s)

#17


2  

It can be done using Numpy library. arange() function allows steps in float. But, it returns a numpy array which can be converted to list using tolist() for our convenience.

它可以使用Numpy库完成。函数的作用是:允许浮动的步骤。但是,它返回一个numpy数组,为了方便,可以使用tolist()将其转换为list。

for i in np.arange(0, 1, 0.1).tolist():   print i

#18


2  

My answer is similar to others using map(), without need of NumPy, and without using lambda (though you could). To get a list of float values from 0.0 to t_max in steps of dt:

我的回答与使用map()的其他人类似,不需要NumPy,也不使用lambda(尽管您可以)。以dt为步骤,从0.0到t_max的浮点值列表:

def xdt(n):    return dt*float(n)tlist  = map(xdt, range(int(t_max/dt)+1))

#19


2  

more_itertools is a third-party library that implements a numeric_range tool:

more_itertools是一个实现numeric_range工具的第三方库:

import more_itertools as mitfor x in mit.numeric_range(0, 1, 0.1):    print("{:.1f}".format(x))

Output

输出

0.00.10.20.30.40.50.60.70.80.9

This tool also works for Decimal and Fraction.

这个工具也适用于小数和小数。

#20


1  

Add auto-correction for the possibility of an incorrect sign on step:

增加自动更正的可能性不正确的标志在步骤:

def frange(start,step,stop):    step *= 2*((stop>start)^(step<0))-1    return [start+i*step for i in range(int((stop-start)/step))]

#21


1  

My solution:

我的解决方案:

def seq(start, stop, step=1, digit=0):    x = float(start)    v = []    while x <= stop:        v.append(round(x,digit))        x += step    return v

#22


1  

The trick to avoid round-off problem is to use a separate number to move through the range, that starts and half the step ahead of start.

避免“四舍五入”问题的诀窍是使用一个单独的数字在开始和开始前的一半的范围内移动。

# floating point rangedef frange(a, b, stp=1.0):  i = a+stp/2.0  while i<b:    yield a    a += stp    i += stp

Alternatively, numpy.arange can be used.

另外,numpy。可以使用论坛。

#23


1  

Best Solution: no rounding error
_________________________________________________________________________________

最好的解决方案:不舍入误差_________________________________________________________________________________

>>> step = .1>>> N = 10     # number of data points>>> [ x / pow(step, -1) for x in range(0, N + 1) ][0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

_________________________________________________________________________________

Or, for a set range instead of set data points (e.g. continuous function), use:

_________________________________________________________________________________或者一组范围而不是设置数据点(如连续函数),使用:

>>> step = .1>>> rnge = 1     # NOTE range = 1, i.e. span of data points>>> N = int(rnge / step>>> [ x / pow(step,-1) for x in range(0, N + 1) ][0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

To implement a function: replace x / pow(step, -1) with f( x / pow(step, -1) ), and define f.
For example:

实现一个函数:将x / pow(step, -1)替换为f(x / pow(step, -1)),定义f。

>>> import math>>> def f(x):        return math.sin(x)>>> step = .1>>> rnge = 1     # NOTE range = 1, i.e. span of data points>>> N = int(rnge / step)>>> [ f( x / pow(step,-1) ) for x in range(0, N + 1) ][0.0, 0.09983341664682815, 0.19866933079506122, 0.29552020666133955, 0.3894183423086505,  0.479425538604203, 0.5646424733950354, 0.644217687237691, 0.7173560908995228, 0.7833269096274834, 0.8414709848078965]

#24


1  

Suprised no-one has yet mentioned the recommended solution in the Python 3 docs:

出乎意料的是,还没有人提到Python 3文档中推荐的解决方案:

See also:

参见:

  • The linspace recipe shows how to implement a lazy version of range that suitable for floating point applications.
  • linspace食谱展示了如何实现一个适用于浮点应用程序的懒惰版本。

Once defined, the recipe is easy to use and does not require numpy or any other external libraries, but functions like numpy.linspace(). Note that rather than a step argument, the third num argument specifies the number of desired values, for example:

一旦定义,该菜谱就很容易使用,不需要numpy或任何其他外部库,而是使用numpy.linspace()之类的函数。注意,与step参数不同,第三个num参数指定所需值的数量,例如:

print(linspace(0, 10, 5))# linspace(0, 10, 5)print(list(linspace(0, 10, 5)))# [0.0, 2.5, 5.0, 7.5, 10]

I quote a modified version of the full Python 3 recipe from Andrew Barnert below:

我引用了来自Andrew Barnert的完整的Python 3食谱的修改版本:

import collections.abcimport numbersclass linspace(collections.abc.Sequence):    """linspace(start, stop, num) -> linspace object    Return a virtual sequence of num numbers from start to stop (inclusive).    If you need a half-open range, use linspace(start, stop, num+1)[:-1].    """    def __init__(self, start, stop, num):        if not isinstance(num, numbers.Integral) or num <= 1:            raise ValueError('num must be an integer > 1')        self.start, self.stop, self.num = start, stop, num        self.step = (stop-start)/(num-1)    def __len__(self):        return self.num    def __getitem__(self, i):        if isinstance(i, slice):            return [self[x] for x in range(*i.indices(len(self)))]        if i < 0:            i = self.num + i        if i >= self.num:            raise IndexError('linspace object index out of range')        if i == self.num-1:            return self.stop        return self.start + i*self.step    def __repr__(self):        return '{}({}, {}, {})'.format(type(self).__name__,                                       self.start, self.stop, self.num)    def __eq__(self, other):        if not isinstance(other, linspace):            return False        return ((self.start, self.stop, self.num) ==                (other.start, other.stop, other.num))    def __ne__(self, other):        return not self==other    def __hash__(self):        return hash((type(self), self.start, self.stop, self.num))

#25


0  

Here is my solution which works fine with float_range(-1, 0, 0.01) and works without floating point representation errors. It is not very fast, but works fine:

下面是我的解决方案,它适用于float_range(- 1,0,0.01),并且没有浮点表示错误。它不是很快,但效果很好:

from decimal import Decimaldef get_multiplier(_from, _to, step):    digits = []    for number in [_from, _to, step]:        pre = Decimal(str(number)) % 1        digit = len(str(pre)) - 2        digits.append(digit)    max_digits = max(digits)    return float(10 ** (max_digits))def float_range(_from, _to, step, include=False):    """Generates a range list of floating point values over the Range [start, stop]       with step size step       include=True - allows to include right value to if possible       !! Works fine with floating point representation !!    """    mult = get_multiplier(_from, _to, step)    # print mult    int_from = int(round(_from * mult))    int_to = int(round(_to * mult))    int_step = int(round(step * mult))    # print int_from,int_to,int_step    if include:        result = range(int_from, int_to + int_step, int_step)        result = [r for r in result if r <= int_to]    else:        result = range(int_from, int_to, int_step)    # print result    float_result = [r / mult for r in result]    return float_resultprint float_range(-1, 0, 0.01,include=False)assert float_range(1.01, 2.06, 5.05 % 1, True) ==\[1.01, 1.06, 1.11, 1.16, 1.21, 1.26, 1.31, 1.36, 1.41, 1.46, 1.51, 1.56, 1.61, 1.66, 1.71, 1.76, 1.81, 1.86, 1.91, 1.96, 2.01, 2.06]assert float_range(1.01, 2.06, 5.05 % 1, False)==\[1.01, 1.06, 1.11, 1.16, 1.21, 1.26, 1.31, 1.36, 1.41, 1.46, 1.51, 1.56, 1.61, 1.66, 1.71, 1.76, 1.81, 1.86, 1.91, 1.96, 2.01]

#26


0  

I am only a beginner, but I had the same problem, when simulating some calculations. Here is how I attempted to work this out, which seems to be working with decimal steps.

我只是个初学者,但在模拟一些计算时,我遇到了同样的问题。下面是我如何计算的,它似乎是用十进制的步骤。

I am also quite lazy and so I found it hard to write my own range function.

我也很懒,所以我发现很难写出我自己的range函数。

Basically what I did is changed my xrange(0.0, 1.0, 0.01) to xrange(0, 100, 1) and used the division by 100.0 inside the loop.I was also concerned, if there will be rounding mistakes. So I decided to test, whether there are any. Now I heard, that if for example 0.01 from a calculation isn't exactly the float 0.01 comparing them should return False (if I am wrong, please let me know).

基本上,我所做的就是将xrange(0.0, 1.0, 0.01)更改为xrange(0,100, 1)并在循环中使用100.0进行除法。我也担心是否会出现四舍五入的错误。所以我决定测试,是否有。现在我听说,如果从计算中得到的0.01不是浮点数0.01,那么它们应该返回False(如果我错了,请告诉我)。

So I decided to test if my solution will work for my range by running a short test:

所以我决定通过一个简短的测试来测试我的解决方案是否适用于我的范围:

for d100 in xrange(0, 100, 1):    d = d100 / 100.0    fl = float("0.00"[:4 - len(str(d100))] + str(d100))    print d, "=", fl , d == fl

And it printed True for each.

每个都打印出来了。

Now, if I'm getting it totally wrong, please let me know.

如果我完全搞错了,请告诉我。

#27


0  

This one liner will not clutter your code. The sign of the step parameter is important.

这一行代码不会打乱你的代码。步骤参数的符号很重要。

def frange(start, stop, step):    return [x*step+start for x in range(0,round(abs((stop-start)/step)+0.5001),        int((stop-start)/step<0)*-2+1)]

#28


0  

frange(start, stop, precision)

纤毛刷(启动、停止、精度)

def frange(a,b,i):    p = 10**i    sr = a*p    er = (b*p) + 1    p = float(p)    return map(lambda x: x/p, xrange(sr,er))In >frange(-1,1,1)Out>[-1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

#29


0  

start and stop are inclusive rather than one or the other (usually stop is excluded) and without imports, and using generators

启动和停止是兼容的,而不是一个或另一个(通常停止被排除),没有导入,并使用生成器。

def rangef(start, stop, step, fround=5):    """    Yields sequence of numbers from start (inclusive) to stop (inclusive)    by step (increment) with rounding set to n digits.    :param start: start of sequence    :param stop: end of sequence    :param step: int or float increment (e.g. 1 or 0.001)    :param fround: float rounding, n decimal places    :return:    """    try:        i = 0        while stop >= start and step > 0:            if i==0:                yield start            elif start >= stop:                yield stop            elif start < stop:                if start == 0:                    yield 0                if start != 0:                    yield start            i += 1            start += step            start = round(start, fround)        else:            pass    except TypeError as e:        yield "type-error({})".format(e)    else:        pass# passingprint(list(rangef(-100.0,10.0,1)))print(list(rangef(-100,0,0.5)))print(list(rangef(-1,1,0.2)))print(list(rangef(-1,1,0.1)))print(list(rangef(-1,1,0.05)))print(list(rangef(-1,1,0.02)))print(list(rangef(-1,1,0.01)))print(list(rangef(-1,1,0.005)))# failing: type-error:print(list(rangef("1","10","1")))print(list(rangef(1,10,"1")))

Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)]

Python 3.6.2 (v3.6.2:5fd33b5, 2017年7月8日,04:57:36)[MSC v.]1900 64位(AMD64))

#30


0  

To counter the float precision issues, you could use the Decimal module.

为了解决浮点精度问题,可以使用Decimal模块。

This demands an extra effort of converting to Decimal from int or float while writing the code, but you can instead pass str and modify the function if that sort of convenience is indeed necessary.

这需要在编写代码时从int或float转换为Decimal,但是如果确实需要这种方便,您可以通过str并修改函数。

from decimal import Decimalfrom decimal import Decimal as Ddef decimal_range(*args):    zero, one = Decimal('0'), Decimal('1')    if len(args) == 1:        start, stop, step = zero, args[0], one    elif len(args) == 2:        start, stop, step = args + (one,)    elif len(args) == 3:        start, stop, step = args    else:        raise ValueError('Expected 1 or 2 arguments, got %s' % len(args))    if not all([type(arg) == Decimal for arg in (start, stop, step)]):        raise ValueError('Arguments must be passed as <type: Decimal>')    # neglect bad cases    if (start == stop) or (start > stop and step >= zero) or \                          (start < stop and step <= zero):        return []    current = start    while abs(current) < abs(stop):        yield current        current += step

Sample outputs -

样本输出-

list(decimal_range(D('2')))# [Decimal('0'), Decimal('1')]list(decimal_range(D('2'), D('4.5')))# [Decimal('2'), Decimal('3'), Decimal('4')]list(decimal_range(D('2'), D('4.5'), D('0.5')))# [Decimal('2'), Decimal('2.5'), Decimal('3.0'), Decimal('3.5'), Decimal('4.0')]list(decimal_range(D('2'), D('4.5'), D('-0.5')))# []list(decimal_range(D('2'), D('-4.5'), D('-0.5')))# [Decimal('2'),#  Decimal('1.5'),#  Decimal('1.0'),#  Decimal('0.5'),#  Decimal('0.0'),#  Decimal('-0.5'),#  Decimal('-1.0'),#  Decimal('-1.5'),#  Decimal('-2.0'),#  Decimal('-2.5'),#  Decimal('-3.0'),#  Decimal('-3.5'),#  Decimal('-4.0')]