在python中创建⼀个具有特定⼤⼩的空列表
本⽂翻译⾃:
I want to create an empty list (or whatever is the best way) that can hold 10 elements. 我想创建⼀个可以容纳10个元素的空列
我想创建⼀个可以容纳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? 有⼈可以解释原因吗?
有⼈可以解释原因吗?
#1楼
#2楼
You can .append(element) to the list, eg: s1.append(i) . 你可以
。 What you are
你可以.append(element)到列表,例如: s1.append(i) 。
currently trying to do is access an element ( s1[i] ) that does not exist. 您当前要做的是访问不存在的元素(
您当前要做的是访问不存在的元素( s1[i] )。
#3楼
Try this instead: 试试这个:
random在python中的意思
试试这个:
lst = [None] * 10
The above will create a list of size 10, where each position is initialized to None . 以上将创建⼀个⼤⼩为10的列表,其中每个位
以上将创建⼀个⼤⼩为10的列表,其中每个位
之后,您可以向其添加元素:
置初始化为None 。
。 After that, you can add elements to it: 之后,您可以向其添加元素:
lst = [None] * 10
for i in range(10):
lst[i] = i
Admittedly, that's not the Pythonic way to do things. 不可否认,这不是Pythonic做事的⽅式。
这样做更好:
不可否认,这不是Pythonic做事的⽅式。 Better do this: 这样做更好:
lst = []
for i in range(10):
lst.append(i)
Or even better , use list comprehensions like this: 或者
或者甚⾄更好 ,使⽤这样的列表推导:
[i for i in range(10)]
#4楼
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
少i+1元素初始化列表,否则不能分配像lst[i] = something的列表。
list. 您需要使⽤append将元素添加到列表的末尾。
您需要使⽤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]创建⼀个列表
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]
#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 [] 但是当我运⾏它时,结果是[]
但是当我运⾏它时,结果是[]
是⽆效的语法; based on your description of what you're seeing, I assume print display s1 is not valid syntax;print display s1是⽆效的语法;
you meant display(s1) and then print s1 . 根据您对所见内容的描述,我假设你的意思是
。 For that to
根据您对所见内容的描述,我假设你的意思是display(s1) ,然后print s1 。
run, you must have previously defined a global s1 to pass into the function. 要运⾏它,您必须先前已定义⼀个全局
要运⾏它,您必须先前已定义⼀个全局s1传递给该函数。
Calling display does not modify the list you pass in, as written. 调⽤
不会像写⼊的那样修改传⼊的列表。 Your code says
调⽤display不会像写⼊的那样修改传⼊的列表。
" 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 ". 你的代码说“
你的代码说“ s1是传递给函数的任何东西的名字;好吧,现在我们要做的第⼀件事就是完全忘记那件事,让s1开始引⽤新创建的list 。现在我们”将修改该list “。This has no effect on the value you passed in. 这对您传⼊的值没有影响。
这对您传⼊的值没有影响。
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. 创建您描述的内容⽆需任何信息,因此请勿传
创建您描述的内容⽆需任何信息,因此请勿传递任何信息。要获取信息,请将其return 。
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
函数会跳过结束点。 (As side notes, [] works 您将注意到的下⼀个问题是您的列表实际上只有9个元素,因为range函数会跳过结束点。
range function. 您将注意到的下⼀个问题是您的列表实际上只有9个元素,因为
just as well as list() , the semicolon is unnecessary, s1 is a poor name for the variable, and only one parameter is needed for
(作为旁注, []的作品⼀样好list()分号是不必要的, s1是变量⼀个可range if you're starting from 0 .) So then you end up with (作为旁注,
怜的名字,并需要对只有⼀个参数range ,如果你从开始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.range是不是有些神奇的关键字这是语⾔的⼀部分的⽅式for与def是,⽽是它的
那是对的 -
并猜猜该函数返回什么? That's right - a list of those integers. 那是对的 -⼀个功能。
⼀个功能。 And guess what that function returns? 并猜猜该函数返回什么?
所以整个功能都崩溃了
这些整数的列表。 So the entire function collapses to 所以整个功能都崩溃了
这些整数的列表。
def create_list():
return range(10)
and now you see why we don't need to write a function ourselves at all; 现在你明⽩为什么我们根本不需要⾃⼰写⼀个函数了;
现在你明⽩为什么我们根本不需要⾃⼰写⼀个函数了;
已经是我们正在寻的功能。 Although, again, there is no need or reason
range is already the function we're looking for.range已经是我们正在寻的功能。
to "pre-size" the list. 虽然,再次,没有必要或理由“预先确定”列表的⼤⼩。
虽然,再次,没有必要或理由“预先确定”列表的⼤⼩。
#6楼
varunl's currently accepted answer varunl⽬前接受的答案
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中的⽰例:
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. 有⼀种默
有⼀种默
认的内置python⽅式(不是编写函数),但我不确定它是什么。 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.3996890

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。