Python 使用循环创建一个列表,用 float() 填充它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20261568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a list using a loop, filling it with float()
提问by Yaga
I'm currently working on a project that requires me to have a list from 0.9 to 1.2 with steps of 0.01. I tried the following:
我目前正在做一个项目,该项目要求我有一个从 0.9 到 1.2 的列表,步长为 0.01。我尝试了以下方法:
init = float(0.9)
l = []
for i in range(0,31):
l[i]= init + ( float(i) / 100 )
However, python gives me the following output:
但是,python 给了我以下输出:
Traceback (most recent call last): File "", line 2, in IndexError: list assignment index out of range
回溯(最近一次调用最后一次):文件“”,第 2 行,在 IndexError 中:列表分配索引超出范围
Can anyone help me solve this problem?
谁能帮我解决这个问题?
回答by Sorin
You need to extend the list. Use:
您需要扩展列表。用:
l.append(init + (float(i)/100))
or
或者
l += [init + (float(i)/100)]
or even the more pythonic way
甚至更pythonic的方式
l = [init + (float(i)/100) for i in range(0, 31)]
回答by e-satis
[]works only if there is an element already at this index the list. Use list.append():
[]仅当此索引列表中已有元素时才有效。使用list.append():
init = float(0.9)
l = []
for i in range(0,31):
l.append(init + ( float(i) / 100 ))
Once you are confortable with this, you can even use a comprehension list :
一旦您对此感到满意,您甚至可以使用理解列表:
l = [init + (float(i) / 100 )) for i in range(0, 31)]
It is very rare in Python to use indexes. I understand a lot people do it because it's an habit in other languages, but most of the time, it's an anti-pattern in Python. If you you see a isomewhere, always wonder if you are not trying to reinvent the wheel.
Python 中很少使用索引。我知道很多人这样做是因为它在其他语言中是一种习惯,但大多数时候,它是 Python 中的一种反模式。如果你看到i某个地方,总是想知道你是不是在试图重新发明轮子。
BTW. Division has priority on addition so no need for parenthesis. Plus, init = float(0.9)is redundant. you can write init = 0.9. And the /always returns a float, therefor you can do :
顺便提一句。除法优先加法,所以不需要括号。另外,init = float(0.9)是多余的。你可以写init = 0.9。并且/总是返回一个浮点数,因此你可以这样做:
l = []
for i in range(0, 31):
l.append(0.9 + i / 100)
Also note the way I place spaces. It's the most used style convention in Python.
还要注意我放置空格的方式。它是Python 中最常用的样式约定。
And with a comprehension list :
并带有一个理解列表:
l = [0.9 + i / 100 for i in range(0, 31)]
It is a much simpler way to achieve what you want. Don't worry, if your code works and you understand it, it's the most important. You don't NEED to do this. I'm just giving you this information so you can use it later if you wish.
这是一种更简单的方法来实现你想要的。不用担心,如果您的代码有效并且您理解它,这是最重要的。你不需要这样做。我只是向您提供此信息,以便您以后需要时可以使用它。
回答by Sudipta
You cannot assign values to list on indexes which do not exist:
您不能将值分配给不存在的索引列表:
>>> abc = []
>>> abc[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
Use append, which appends the value in the list i.e. assigns it to the next index.
使用append,它将值附加到列表中,即将它分配给下一个索引。
Or this can also be easily done using list comprehension:
或者这也可以使用列表理解轻松完成:
>>> [ round(float(0.9) + (float(i) / 100 ),2) for i in range(0,31)]
[0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0, 1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 1.07, 1.08, 1.09, 1.1, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16, 1.17, 1.18, 1.19, 1.2]
Note: I have used round to round everything up to 2 decimal digits. You can remove that part, if you don't need it.
注意:我使用 round 将所有内容四舍五入到 2 个十进制数字。如果不需要,可以删除该部分。
回答by Fredrik Pihl
Use the itertoolsmodule:
使用itertools模块:
In [8]: for i in itertools.count(0.9, 0.01):
...: print i
...: if i > 1.2:
...: break
...:
0.9
0.91
0.92
0.93
.
.
.
1.18
1.19
1.2
As pointed out in the comments, the count()can be combined with a takewhilein order to create a list-comprehension:
正如评论中所指出的,count()可以结合使用时间来创建列表理解:
[i for i in itertools.takewhile(lambda x: x <= 1.2, itertools.count(0.9, 0.01))]
回答by Peter DeGlopper
Unless I am overlooking something, you can do this with a list comprehension:
除非我忽略了某些东西,否则您可以使用列表理解来做到这一点:
init = float(0.9)
l = [init + (float(i) / 100) for i in range(31)]
Whatever solution you end up using, consider floating point error and maybe use the decimal.Decimalclass instead of floats. All solutions I tested with floating points produced rounding errors, eg:
无论您最终使用什么解决方案,请考虑浮点错误,并可能使用decimal.Decimal类而不是浮点数。我用浮点测试的所有解决方案都会产生舍入误差,例如:
>>> l
[0.9, 0.91, 0.92, 0.93, 0.9400000000000001, ...]
回答by Siddharth Menon
Consider appending the values to the list using l.append(), like this:
考虑使用 l.append() 将值附加到列表中,如下所示:
init = float(0.9)
l = []
for i in range(0,31):
a = init + (float(i)/100)
l.append(a)
Edit:There is another way to do this, without using any list functions and just the random function (although the previous method is probably easier). Basically, you just create a random list and then replace the values in the list with the required values. Take a look:
编辑:还有另一种方法可以做到这一点,不使用任何列表函数而只使用随机函数(尽管前一种方法可能更容易)。基本上,您只需创建一个随机列表,然后将列表中的值替换为所需的值。看一看:
import random
init = float(0.9)
l = [random.random() for i in range(0,31)]
for i in range(0,31):
l[i]= init + ( float(i) / 100 )
print l
It should work this way as well. But, this is only if you don't want to use any list functions. Still, the first script is easier and probably better.
它也应该以这种方式工作。但是,这仅适用于您不想使用任何列表函数的情况。尽管如此,第一个脚本更容易,而且可能更好。
回答by glglgl
About .append()you already was informed.
关于.append()你已经被告知。
But there is another point: Due to the fact that .01cannot be represented in floatin point exactly, keeping on adding .01will sum up this error.
但是还有一点:由于.01不能精确地用浮点数表示,继续添加.01会总结这个错误。
More exact would be to do
更准确的做法是
init = float(0.9)
end = float(1.21)
steps = 31
l = []
for i in range(0,31):
l.append((init * (steps - i) + end * i) / steps)
回答by Nilesh
Try This- :
尝试这个- :
init = float(0.9)
l = [init + ( float(i) / 100 ) for i in range(0,31)]
It will work :)
它会工作:)
回答by gaurav kumar
Everyone has given great answers however I thought why not a general function to solve this problem i.e without knowing the range in advance (in this case range is 0-31)
每个人都给出了很好的答案,但是我想为什么不是解决这个问题的通用函数,即事先不知道范围(在这种情况下范围是 0-31)
>>> l=[]
>>> l=[]
>>> def addNumFun(startRange, endRange, interval):
init = str(interval)[::-1].find('.')
start = int(startRange * (10**init))
end = int(endRange * (10**init))
for i in range(start,end):
l.append(i/(10**init))
l.append(end/(10**init)) # to add the last number of range
>>> addNumFun(0.9,1.2,0.01)
>>> l
[0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0, 1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 1.07, 1.08, 1.09, 1.1, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16, 1.17, 1.18, 1.19, 1.2, 0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0, 1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 1.07, 1.08, 1.09, 1.1, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16, 1.17, 1.18, 1.19, 1.2]

