Python 创建一个包含 100 个整数的列表,其值等于它们的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19019005/
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
Create a list of 100 integers whose values equal their indexes
提问by Bob
Create a list of 100 integers whose value and index are the same, e.g.
创建一个包含 100 个值和索引相同的整数的列表,例如
mylist[0] = 0, mylist[1] = 1, mylist[2] = 2, ...
Here is my code.
这是我的代码。
x_list=[]
def list_append(x_list):
for i in 100:
x_list.append(i)
return(list_append())
print(x_list)
采纳答案by Veedrac
Since nobody else realised you're using Python 3, I'll point out that you should be doing list(range(100))
to get the wanted behaviour.
由于没有其他人意识到您使用的是 Python 3,我会指出您应该这样做list(range(100))
以获得所需的行为。
回答by TerryA
for i in 100
doesn't do what you think it does. int
objects are not iterable, so this won't work. The for-loop tries to iterate through the object given.
for i in 100
不会做你认为它会做的事情。int
对象不可迭代,所以这行不通。for 循环尝试遍历给定的对象。
If you want to get a list of numbers between 0-100, use range()
:
如果您想获取 0-100 之间的数字列表,请使用range()
:
for i in range(100):
dostuff()
The answer to your question is pretty much range(100)
anyway:
range(100)
无论如何,您的问题的答案几乎是:
>>> range(100)[0]
0
>>> range(100)[64]
64
回答by Andreas Jung
Use range() for generating such a list
使用 range() 生成这样的列表
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(10)[5]
5
回答by tom10
You can use range(100)
, but it seems that you are probably looking to make the list from scratch, so there you can use while
:
您可以使用range(100)
,但似乎您可能希望从头开始制作列表,因此您可以使用while
:
x_list=[]
i = 0
while i<100:
x_list.append(i)
i += 1
Or you could do this recursively:
或者您可以递归地执行此操作:
def list_append(i, L):
L.append(i)
if i==99:
return L
list_append(i+1, L)
x_list = []
list_append(0, x_list)
print x_list
回答by PiMathCLanguage
If you want to import numpy
you could do something like this:
如果要导入numpy
,可以执行以下操作:
import numpy as np
x_list = np.arange(0, 100).tolist()
Should work in python2.7 and python3.x
应该在 python2.7 和 python3.x 中工作
回答by codingBoy
Also can use List Comprehensions, like
也可以使用列表理解,比如
[x for x in range(100)]
回答by zyxwvutsr qpnmlkj
import random
data1=[]
def f(x):
return(random.randrange(0,1000))
for x in range (0,100):
data1.append(f(x))
data1