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

您所在的位置:网站首页 python创建空字典里的空列表 在python中创建一个具有特定大小的空列表

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

2024-07-15 14:01| 来源: 网络整理| 查看: 265

本文翻译自: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? 有人可以解释原因吗?

#1楼

参考:https://stackoom.com/question/iwgE/在python中创建一个具有特定大小的空列表

#2楼

You can .append(element) to the list, eg: s1.append(i) . 你可以.append(element)到列表,例如: s1.append(i) 。 What you are currently trying to do is access an element ( s1[i] ) that does not exist. 您当前要做的是访问不存在的元素( s1[i] )。

#3楼

Try this instead: 试试这个:

lst = [None] * 10

The above will create a list of size 10, where each position is initialized to None . 以上将创建一个大小为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做事的方式。 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. 除非已使用至少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] #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; print display s1是无效的语法; based on your description of what you're seeing, I assume you meant display(s1) and then print s1 . 根据您对所见内容的描述,我假设你的意思是display(s1) ,然后print s1 。 For that to 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. 调用display不会像写入的那样修改传入的列表。 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 ". 你的代码说“ 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 range function. 您将注意到的下一个问题是您的列表实际上只有9个元素,因为range函数会跳过结束点。 (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 (作为旁注, []的作品一样好list()分号是不必要的, s1是变量一个可怜的名字,并需要对只有一个参数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是,而是它的一个功能。 And guess what that function returns? 并猜猜该函数返回什么? That's right - a list of those integers. 那是对的 - 这些整数的列表。 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; 现在你明白为什么我们根本不需要自己写一个函数了; range is already the function we're looking for. range已经是我们正在寻找的功能。 Although, again, there is no need or reason to "pre-size" the list. 虽然,再次,没有必要或理由“预先确定”列表的大小。

#6楼

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. 有一种默认的内置python方式(不是编写函数),但我不确定它是什么。 Would be happy to be corrected! 很乐意纠正!

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


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3