在python中创建一个具有特定大小的空列表

时间:2022-09-20 21:28:36

I want to create an empty list (or whatever is the best way) that can hold 10 elements.

我想创建一个可以容纳10个元素的空列表(或者任何最好的方法)。

After that I want to assign values in that list, for example this is supposed to display 0 to 9:

之后我想在列表中赋值,例如这个应该显示0到9:

s1 = list();
for i in range(0,9):
   s1[i] = i

print  s1

But when I run this code, it generates an error or in another case it just displays [] (empty).

但是当我运行这段代码时,它会产生一个错误,或者在另一种情况下,它只显示[](空)。

Can someone explain why?

有人能解释一下为什么?

12 个解决方案

#1


457  

You cannot assign to a list like lst[i] = something. You need to use append. lst.append(something).

不能给一个列表赋值,比如lst[i] = something。您需要使用append。lst.append(的东西)。

(You could use the assignment notation if you were using a dictionary).

(如果你使用字典,你可以使用赋值符号)。

Creating an empty list:

创建一个空列表:

>>> l = [None] * 10
>>> l
[None, None, None, None, None, None, None, None, None, None]

range(x) creates a list from [0, 1, 2, ... x-1]

range(x)从[0,1,2,…]创建一个列表。x - 1)

# 2.X only. Use list(range(10)) in 3.X.
>>> l = range(10)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Using a function to create a list:

使用函数创建列表:

>>> def display():
...     s1 = []
...     for i in range(9): # This is just to tell you how to create a list.
...         s1.append(i)
...     return s1
... 
>>> print display()
[0, 1, 2, 3, 4, 5, 6, 7, 8]

List comprehension (Using the squares because for range you don't need to do all this, you can just return range(0,9) ):

列表理解(使用平方因为对于范围你不需要做所有这些,你可以只返回范围(0,9)):

>>> def display():
...     return [x**2 for x in range(9)]
... 
>>> print display()
[0, 1, 4, 9, 16, 25, 36, 49, 64]

#2


82  

Try this instead:

试试这个:

lst = [None] * 10

The above will create a list of size 10, where each position is initialized to None. After that, you can add elements to it:

上面将创建一个大小为10的列表,其中每个位置都被初始化为None。在那之后,您可以添加元素到它:

lst = [None] * 10
for i in range(10):
    lst[i] = i

Admittedly, that's not the Pythonic way to do things. Better do this:

不可否认,这不是python的做事方式。更好的做到这一点:

lst = []
for i in range(10):
    lst.append(i)

Or even better, use list comprehensions like this:

或者更好的是,使用像这样的列表理解:

[i for i in range(10)]

#3


42  

varunl's currently accepted answer

varunl目前接受的答案

 >>> l = [None] * 10
 >>> l
 [None, None, None, None, None, None, None, None, None, None]

Works well for non-reference types like numbers. Unfortunately if you want to create a list-of-lists you will run into referencing errors. Example in Python 2.7.6:

对于像数字这样的非引用类型,这种方法很有效。不幸的是,如果您想创建列表列表,您将遇到引用错误。在Python中2.7.6示例:

>>> a = [[]]*10
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> a[0].append(0)
>>> a
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]
>>> 

As you can see, each element is pointing to the same list object. To get around this, you can create a method that will initialize each position to a different object reference.

如您所见,每个元素都指向同一个列表对象。要解决这个问题,您可以创建一个方法,将每个位置初始化为不同的对象引用。

def init_list_of_objects(size):
    list_of_objects = list()
    for i in range(0,size):
        list_of_objects.append( list() ) #different object reference each time
    return list_of_objects


>>> a = init_list_of_objects(10)
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> a[0].append(0)
>>> a
[[0], [], [], [], [], [], [], [], [], []]
>>> 

There is likely a default, built-in python way of doing this (instead of writing a function), but I'm not sure what it is. Would be happy to be corrected!

可能有一种默认的、内置的python方法来实现这一点(而不是编写函数),但我不确定它是什么。很高兴被纠正!

Edit: It's [ [] for _ in range(10)]

编辑:[]for _ in range(10)]

Example :

例子:

>>> [ [random.random() for _ in range(2) ] for _ in range(5)]
>>> [[0.7528051908943816, 0.4325669600055032], [0.510983236521753, 0.7789949902294716], [0.09475179523690558, 0.30216475640534635], [0.3996890132468158, 0.6374322093017013], [0.3374204010027543, 0.4514925173253973]]

#4


16  

You can .append(element) to the list, e.g.: s1.append(i). What you are currently trying to do is access an element (s1[i]) that does not exist.

你可以在列表中添加(元素),例如:s1.append(i)。您目前正在尝试访问一个不存在的元素(s1[i])。

#5


9  

There are two "quick" methods:

有两种“快速”方法:

x = length_of_your_list
a = [None]*x
# or
a = [None for _ in xrange(x)]

It appears that [None]*x is faster:

[None]*x似乎更快:

>>> from timeit import timeit
>>> timeit("[None]*100",number=10000)
0.023542165756225586
>>> timeit("[None for _ in xrange(100)]",number=10000)
0.07616496086120605

But if you are ok with a range (e.g. [0,1,2,3,...,x-1]), then range(x) might be fastest:

但是如果你对一个范围(例如[0,1,2,3,…,x-1]没有问题,那么范围(x)可能是最快的:

>>> timeit("range(100)",number=10000)
0.012513160705566406

#6


5  

(This was written based on the original version of the question.)

(这是根据问题的原始版本写成的。)

I want to create a empty list (or whatever is the best way) can hold 10 elements.

我想创建一个空列表(或者任何最好的方法)可以容纳10个元素。

All lists can hold as many elements as you like, subject only to the limit of available memory. The only "size" of a list that matters is the number of elements currently in it.

所有列表可以容纳任意多的元素,只受可用内存的限制。列表中唯一重要的“大小”是当前的元素数量。

but when I run it, the result is []

但是当我运行它时,结果是

print display s1 is not valid syntax; based on your description of what you're seeing, I assume you meant display(s1) and then print s1. For that to run, you must have previously defined a global s1 to pass into the function.

打印显示s1不是有效语法;根据您对所看到内容的描述,我假设您是指display(s1)然后打印s1。要运行它,您必须预先定义一个全局s1来传递到函数中。

Calling display does not modify the list you pass in, as written. Your code says "s1 is a name for whatever thing was passed in to the function; ok, now the first thing we'll do is forget about that thing completely, and let s1 start referring instead to a newly created list. Now we'll modify that list". This has no effect on the value you passed in.

调用display不会修改您传入的列表(如已写入)。你的代码说"s1是传递给函数的任何东西的名字;好的,现在我们要做的第一件事是完全忘记那个东西,让s1开始引用一个新创建的列表。现在我们来修改这个列表。这对您传入的值没有影响。

There is no reason to pass in a value here. (There is no real reason to create a function, either, but that's beside the point.) You want to "create" something, so that is the output of your function. No information is required to create the thing you describe, so don't pass any information in. To get information out, return it.

没有理由在这里传递一个值。(创建函数也没有真正的理由,但这无关紧要。)你想要“创建”一些东西,这就是你的函数的输出。创建所描述的东西不需要任何信息,所以不要传递任何信息。要获取信息,请返回它。

That would give you something like:

这会给你一些类似的东西:

def display():
    s1 = list();
    for i in range(0, 9):
        s1[i] = i
    return s1

The next problem you will note is that your list will actually have only 9 elements, because the end point is skipped by the range function. (As side notes, [] works just as well as list(), the semicolon is unnecessary, s1 is a poor name for the variable, and only one parameter is needed for range if you're starting from 0.) So then you end up with

您将注意到的下一个问题是,您的列表实际上只有9个元素,因为range函数跳过了端点。(如边注,[]和list()一样有效,不需要分号,s1是变量的糟糕名称,如果从0开始,那么范围只需要一个参数)。然后你得到

def create_list():
    result = list()
    for i in range(10):
        result[i] = i
    return result

However, this is still missing the mark; range is not some magical keyword that's part of the language the way for and def are, but instead it's a function. And guess what that function returns? That's right - a list of those integers. So the entire function collapses to

然而,这仍未达到目标;range不是某种不可思议的关键字,它是语言的一部分,而def是,但它是一个函数。猜猜这个函数会返回什么?对,就是这些整数的列表。所以整个函数坍缩到

def create_list():
    return range(10)

and now you see why we don't need to write a function ourselves at all; range is already the function we're looking for. Although, again, there is no need or reason to "pre-size" the list.

现在你知道为什么我们不需要自己写一个函数了;范围已经是我们要找的函数了。尽管,同样,没有必要或理由对列表进行“预缩”。

#7


5  

I'm surprised nobody suggest this simple approach to creating a list of empty lists. This is an old thread, but just adding this for completeness. This will create a list of 10 empty lists

我很惊讶没有人提出创建空列表的简单方法。这是一个旧的线程,只是为了完整性添加它。这将创建一个包含10个空列表的列表

x = [[] for i in range(10)]

#8


2  

Here's my code for 2D list in python which would read no. of rows from the input :

这是我用python编写的2D列表的代码,它将会是no。来自输入的行数:

empty = []
row = int(input())

for i in range(row):
    temp = list(map(int, input().split()))
    empty.append(temp)

for i in empty:
    for j in i:
        print(j, end=' ')
    print('')

#9


1  

Adding to the amazing answers written above,

加上上面令人惊叹的答案,

To simply create an empty list, supposedly with "zeroes" use,

要创建一个空列表,假设使用“0”,

lst=[0]*size

#10


0  

I came across this SO question while searching for a similar problem. I had to build a 2D array and then replace some elements of each list (in 2D array) with elements from a dict. I then came across this SO question which helped me, maybe this will help other beginners to get around. The key trick was to initialize the 2D array as an numpy array and then using array[i,j] instead of array[i][j].

我在寻找类似问题时遇到了这个SO问题。我需要构建一个2D数组,然后用一个dict类型的元素替换每个列表中的一些元素(2D数组)。关键的技巧是将2D数组初始化为一个numpy数组,然后使用数组[i,j]代替array[i][j]。

For reference this is the piece of code where I had to use this :

作为参考,这是我必须使用的一段代码:

nd_array = []
for i in range(30):
    nd_array.append(np.zeros(shape = (32,1)))
new_array = []
for i in range(len(lines)):
    new_array.append(nd_array)
new_array = np.asarray(new_array)
for i in range(len(lines)):
    splits = lines[i].split(' ')
    for j in range(len(splits)):
        #print(new_array[i][j])
        new_array[i,j] = final_embeddings[dictionary[str(splits[j])]-1].reshape(32,1)

Now I know we can use list comprehension but for simplicity sake I am using a nested for loop. Hope this helps others who come across this post.

现在我知道我们可以使用列表理解,但是为了简单起见,我使用了嵌套for循环。希望这能帮助那些遇到这篇文章的人。

#11


0  

This code generates an array that contains 10 random numbers.

该代码生成一个包含10个随机数的数组。

import random
numrand=[]
for i in range(0,10):
   a = random.randint(1,50)
   numrand.append(a)
   print(a,i)
print(numrand)

#12


-1  

s1 = []
for i in range(11):
   s1.append(i)

print s1

To create a list, just use these brackets: "[]"

要创建列表,只需使用这些括号:"[]"

To add something to a list, use list.append()

要向列表添加内容,请使用list.append()

#1


457  

You cannot assign to a list like lst[i] = something. You need to use append. lst.append(something).

不能给一个列表赋值,比如lst[i] = something。您需要使用append。lst.append(的东西)。

(You could use the assignment notation if you were using a dictionary).

(如果你使用字典,你可以使用赋值符号)。

Creating an empty list:

创建一个空列表:

>>> l = [None] * 10
>>> l
[None, None, None, None, None, None, None, None, None, None]

range(x) creates a list from [0, 1, 2, ... x-1]

range(x)从[0,1,2,…]创建一个列表。x - 1)

# 2.X only. Use list(range(10)) in 3.X.
>>> l = range(10)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Using a function to create a list:

使用函数创建列表:

>>> def display():
...     s1 = []
...     for i in range(9): # This is just to tell you how to create a list.
...         s1.append(i)
...     return s1
... 
>>> print display()
[0, 1, 2, 3, 4, 5, 6, 7, 8]

List comprehension (Using the squares because for range you don't need to do all this, you can just return range(0,9) ):

列表理解(使用平方因为对于范围你不需要做所有这些,你可以只返回范围(0,9)):

>>> def display():
...     return [x**2 for x in range(9)]
... 
>>> print display()
[0, 1, 4, 9, 16, 25, 36, 49, 64]

#2


82  

Try this instead:

试试这个:

lst = [None] * 10

The above will create a list of size 10, where each position is initialized to None. After that, you can add elements to it:

上面将创建一个大小为10的列表,其中每个位置都被初始化为None。在那之后,您可以添加元素到它:

lst = [None] * 10
for i in range(10):
    lst[i] = i

Admittedly, that's not the Pythonic way to do things. Better do this:

不可否认,这不是python的做事方式。更好的做到这一点:

lst = []
for i in range(10):
    lst.append(i)

Or even better, use list comprehensions like this:

或者更好的是,使用像这样的列表理解:

[i for i in range(10)]

#3


42  

varunl's currently accepted answer

varunl目前接受的答案

 >>> l = [None] * 10
 >>> l
 [None, None, None, None, None, None, None, None, None, None]

Works well for non-reference types like numbers. Unfortunately if you want to create a list-of-lists you will run into referencing errors. Example in Python 2.7.6:

对于像数字这样的非引用类型,这种方法很有效。不幸的是,如果您想创建列表列表,您将遇到引用错误。在Python中2.7.6示例:

>>> a = [[]]*10
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> a[0].append(0)
>>> a
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]
>>> 

As you can see, each element is pointing to the same list object. To get around this, you can create a method that will initialize each position to a different object reference.

如您所见,每个元素都指向同一个列表对象。要解决这个问题,您可以创建一个方法,将每个位置初始化为不同的对象引用。

def init_list_of_objects(size):
    list_of_objects = list()
    for i in range(0,size):
        list_of_objects.append( list() ) #different object reference each time
    return list_of_objects


>>> a = init_list_of_objects(10)
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> a[0].append(0)
>>> a
[[0], [], [], [], [], [], [], [], [], []]
>>> 

There is likely a default, built-in python way of doing this (instead of writing a function), but I'm not sure what it is. Would be happy to be corrected!

可能有一种默认的、内置的python方法来实现这一点(而不是编写函数),但我不确定它是什么。很高兴被纠正!

Edit: It's [ [] for _ in range(10)]

编辑:[]for _ in range(10)]

Example :

例子:

>>> [ [random.random() for _ in range(2) ] for _ in range(5)]
>>> [[0.7528051908943816, 0.4325669600055032], [0.510983236521753, 0.7789949902294716], [0.09475179523690558, 0.30216475640534635], [0.3996890132468158, 0.6374322093017013], [0.3374204010027543, 0.4514925173253973]]

#4


16  

You can .append(element) to the list, e.g.: s1.append(i). What you are currently trying to do is access an element (s1[i]) that does not exist.

你可以在列表中添加(元素),例如:s1.append(i)。您目前正在尝试访问一个不存在的元素(s1[i])。

#5


9  

There are two "quick" methods:

有两种“快速”方法:

x = length_of_your_list
a = [None]*x
# or
a = [None for _ in xrange(x)]

It appears that [None]*x is faster:

[None]*x似乎更快:

>>> from timeit import timeit
>>> timeit("[None]*100",number=10000)
0.023542165756225586
>>> timeit("[None for _ in xrange(100)]",number=10000)
0.07616496086120605

But if you are ok with a range (e.g. [0,1,2,3,...,x-1]), then range(x) might be fastest:

但是如果你对一个范围(例如[0,1,2,3,…,x-1]没有问题,那么范围(x)可能是最快的:

>>> timeit("range(100)",number=10000)
0.012513160705566406

#6


5  

(This was written based on the original version of the question.)

(这是根据问题的原始版本写成的。)

I want to create a empty list (or whatever is the best way) can hold 10 elements.

我想创建一个空列表(或者任何最好的方法)可以容纳10个元素。

All lists can hold as many elements as you like, subject only to the limit of available memory. The only "size" of a list that matters is the number of elements currently in it.

所有列表可以容纳任意多的元素,只受可用内存的限制。列表中唯一重要的“大小”是当前的元素数量。

but when I run it, the result is []

但是当我运行它时,结果是

print display s1 is not valid syntax; based on your description of what you're seeing, I assume you meant display(s1) and then print s1. For that to run, you must have previously defined a global s1 to pass into the function.

打印显示s1不是有效语法;根据您对所看到内容的描述,我假设您是指display(s1)然后打印s1。要运行它,您必须预先定义一个全局s1来传递到函数中。

Calling display does not modify the list you pass in, as written. Your code says "s1 is a name for whatever thing was passed in to the function; ok, now the first thing we'll do is forget about that thing completely, and let s1 start referring instead to a newly created list. Now we'll modify that list". This has no effect on the value you passed in.

调用display不会修改您传入的列表(如已写入)。你的代码说"s1是传递给函数的任何东西的名字;好的,现在我们要做的第一件事是完全忘记那个东西,让s1开始引用一个新创建的列表。现在我们来修改这个列表。这对您传入的值没有影响。

There is no reason to pass in a value here. (There is no real reason to create a function, either, but that's beside the point.) You want to "create" something, so that is the output of your function. No information is required to create the thing you describe, so don't pass any information in. To get information out, return it.

没有理由在这里传递一个值。(创建函数也没有真正的理由,但这无关紧要。)你想要“创建”一些东西,这就是你的函数的输出。创建所描述的东西不需要任何信息,所以不要传递任何信息。要获取信息,请返回它。

That would give you something like:

这会给你一些类似的东西:

def display():
    s1 = list();
    for i in range(0, 9):
        s1[i] = i
    return s1

The next problem you will note is that your list will actually have only 9 elements, because the end point is skipped by the range function. (As side notes, [] works just as well as list(), the semicolon is unnecessary, s1 is a poor name for the variable, and only one parameter is needed for range if you're starting from 0.) So then you end up with

您将注意到的下一个问题是,您的列表实际上只有9个元素,因为range函数跳过了端点。(如边注,[]和list()一样有效,不需要分号,s1是变量的糟糕名称,如果从0开始,那么范围只需要一个参数)。然后你得到

def create_list():
    result = list()
    for i in range(10):
        result[i] = i
    return result

However, this is still missing the mark; range is not some magical keyword that's part of the language the way for and def are, but instead it's a function. And guess what that function returns? That's right - a list of those integers. So the entire function collapses to

然而,这仍未达到目标;range不是某种不可思议的关键字,它是语言的一部分,而def是,但它是一个函数。猜猜这个函数会返回什么?对,就是这些整数的列表。所以整个函数坍缩到

def create_list():
    return range(10)

and now you see why we don't need to write a function ourselves at all; range is already the function we're looking for. Although, again, there is no need or reason to "pre-size" the list.

现在你知道为什么我们不需要自己写一个函数了;范围已经是我们要找的函数了。尽管,同样,没有必要或理由对列表进行“预缩”。

#7


5  

I'm surprised nobody suggest this simple approach to creating a list of empty lists. This is an old thread, but just adding this for completeness. This will create a list of 10 empty lists

我很惊讶没有人提出创建空列表的简单方法。这是一个旧的线程,只是为了完整性添加它。这将创建一个包含10个空列表的列表

x = [[] for i in range(10)]

#8


2  

Here's my code for 2D list in python which would read no. of rows from the input :

这是我用python编写的2D列表的代码,它将会是no。来自输入的行数:

empty = []
row = int(input())

for i in range(row):
    temp = list(map(int, input().split()))
    empty.append(temp)

for i in empty:
    for j in i:
        print(j, end=' ')
    print('')

#9


1  

Adding to the amazing answers written above,

加上上面令人惊叹的答案,

To simply create an empty list, supposedly with "zeroes" use,

要创建一个空列表,假设使用“0”,

lst=[0]*size

#10


0  

I came across this SO question while searching for a similar problem. I had to build a 2D array and then replace some elements of each list (in 2D array) with elements from a dict. I then came across this SO question which helped me, maybe this will help other beginners to get around. The key trick was to initialize the 2D array as an numpy array and then using array[i,j] instead of array[i][j].

我在寻找类似问题时遇到了这个SO问题。我需要构建一个2D数组,然后用一个dict类型的元素替换每个列表中的一些元素(2D数组)。关键的技巧是将2D数组初始化为一个numpy数组,然后使用数组[i,j]代替array[i][j]。

For reference this is the piece of code where I had to use this :

作为参考,这是我必须使用的一段代码:

nd_array = []
for i in range(30):
    nd_array.append(np.zeros(shape = (32,1)))
new_array = []
for i in range(len(lines)):
    new_array.append(nd_array)
new_array = np.asarray(new_array)
for i in range(len(lines)):
    splits = lines[i].split(' ')
    for j in range(len(splits)):
        #print(new_array[i][j])
        new_array[i,j] = final_embeddings[dictionary[str(splits[j])]-1].reshape(32,1)

Now I know we can use list comprehension but for simplicity sake I am using a nested for loop. Hope this helps others who come across this post.

现在我知道我们可以使用列表理解,但是为了简单起见,我使用了嵌套for循环。希望这能帮助那些遇到这篇文章的人。

#11


0  

This code generates an array that contains 10 random numbers.

该代码生成一个包含10个随机数的数组。

import random
numrand=[]
for i in range(0,10):
   a = random.randint(1,50)
   numrand.append(a)
   print(a,i)
print(numrand)

#12


-1  

s1 = []
for i in range(11):
   s1.append(i)

print s1

To create a list, just use these brackets: "[]"

要创建列表,只需使用这些括号:"[]"

To add something to a list, use list.append()

要向列表添加内容,请使用list.append()