Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

python - 在python中创建一个具有特定大小的空列表(Create an empty list in python with certain size)

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?

(有人可以解释原因吗?)

  ask by Ronaldinho Learn Coding translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You cannot assign to a list like lst[i] = something , unless the list already is initialized with at least i+1 elements.

(除非已使用至少i+1元素初始化列表,否则不能分配像lst[i] = something的列表。)

You need to use append to add elements to the end of the list.

(您需要使用append将元素添加到列表的末尾。)

lst.append(something) .

(lst.append(something) 。)

(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]

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]

Keep in mind that something like l[15] = 5 would still fail, as our list has only 10 elements.

(请记住,像l[15] = 5这样的东西仍然会失败,因为我们的列表只有10个元素。)

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...