在 Python 中创建一个具有特定大小的空列表 [英] Create an empty list in Python with certain size

查看:37
本文介绍了在 Python 中创建一个具有特定大小的空列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

s1 = list();对于范围内的 i (0,9):s1[i] = i打印 s1

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

有人能解释一下原因吗?

解决方案

您不能分配给像 lst[i] = something 这样的列表,除非该列表已经用至少 初始化i+1 元素.您需要使用 append 将元素添加到列表的末尾.lst.append(something).

(如果您使用字典,则可以使用赋值符号).

创建一个空列表:

<预><代码>>>>l = [无] * 10>>>升[无、无、无、无、无、无、无、无、无、无]

为上述列表的现有元素赋值:

<预><代码>>>>l[1] = 5>>>升[无,5,无,无,无,无,无,无,无,无]

请记住,像 l[15] = 5 这样的操作仍然会失败,因为我们的列表只有 10 个元素.

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

# 仅适用于 2.X.在 3.X 中使用 list(range(10)).>>>l = 范围(10)>>>升[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

使用函数创建列表:

<预><代码>>>>定义显示():... s1 = []... for i in range(9): # 这只是告诉你如何创建一个列表.... s1.append(i)...返回s1...>>>打印显示()[0, 1, 2, 3, 4, 5, 6, 7, 8]

列表理解(使用正方形是因为对于范围,您不需要执行所有这些操作,您只需返回 range(0,9) ):

<预><代码>>>>定义显示():...返回 [x**2 for x in range(9)]...>>>打印显示()[0, 1, 4, 9, 16, 25, 36, 49, 64]

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

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?

解决方案

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

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.

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]

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

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

这篇关于在 Python 中创建一个具有特定大小的空列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆