在python中创建具有特定大小的空列表 [英] Create an empty list in python with certain size
问题描述
我想创建一个可以容纳10个元素的空列表(或最好的方法).
I want to create an empty list (or whatever is the best way) that can hold 10 elements.
之后,我想在该列表中分配值,例如应该显示0到9:
After that I want to assign values in that list, for example this is supposed to display 0 to 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?
推荐答案
除非已使用至少i+1
个元素初始化了列表,否则您无法分配给类似lst[i] = something
的列表.您需要使用append将元素添加到列表的末尾. lst.append(something)
.
You cannot assign to a list like lst[i] = something
, unless the list already is initialized with at least i+1
elements. You need to use append to add elements to the end of the list. lst.append(something)
.
(如果您使用字典,则可以使用分配符号).
(You could use the assignment notation if you were using a dictionary).
创建一个空列表:
>>> l = [None] * 10
>>> l
[None, None, None, None, None, None, None, None, None, None]
为上述列表中的现有元素分配值:
Assigning a value to an existing element of the above list:
>>> l[1] = 5
>>> l
[None, 5, None, None, None, None, None, None, None, None]
请记住,由于l[15] = 5
之类的列表只有10个元素,因此仍然会失败.
Keep in mind that something like l[15] = 5
would still fail, as our list has only 10 elements.
range(x)从[0,1,2,... x-1]创建一个列表
range(x) creates a list from [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]
使用函数创建列表:
>>> 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]
列表理解(使用正方形,因为对于范围您不需要执行所有这些操作,您只需返回range(0,9)
即可):
List comprehension (Using the squares because for range you don't need to do all this, you can just return range(0,9)
):
>>> def display():
... return [x**2 for x in range(9)]
...
>>> print display()
[0, 1, 4, 9, 16, 25, 36, 49, 64]
这篇关于在python中创建具有特定大小的空列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!