简体   繁体   中英

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

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(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. int objects are not iterable, so this won't work. The for-loop tries to iterate through the object given.

If you want to get a list of numbers between 0-100, use range() :

for i in range(100):
    dostuff()

The answer to your question is pretty much range(100) anyway:

>>> 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 :

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:

import numpy as np

x_list = np.arange(0, 100).tolist()

Should work in python2.7 and python3.x

import random
data1=[]
def f(x):
    return(random.randrange(0,1000))
for x in range (0,100):
    data1.append(f(x))

data1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM