[英]Create a list of 100 integers whose values equal their indexes
Create a list of 100 integers whose value and index are the same, eg创建一个包含 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)
由于没有其他人意识到您正在使用 Python 3,我将指出您应该执行list(range(100))
以获得所需的行为。
Use range() for generating such a list使用 range() 生成这样的列表
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(10)[5]
5
for i in 100
doesn't do what you think it does. for i in 100
不会做你认为它会做的事情。 int
objects are not iterable, so this won't work. int
对象不可迭代,所以这行不通。 The for-loop tries to iterate through the object given. 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
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
也可以使用列表理解,比如
[x for x in range(100)]
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 中工作
import random
data1=[]
def f(x):
return(random.randrange(0,1000))
for x in range (0,100):
data1.append(f(x))
data1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.