问题:在python中创建具有特定大小的空列表
我想创建一个可以容纳10个元素的空列表(或最好的方法)。
之后,我想在该列表中分配值,例如,应该显示0到9:
s1 = list();
for i in range(0,9):
s1[i] = i
print s1
但是当我运行此代码时,它会生成错误,或者在其他情况下,它只会显示 []
(空)。
有人可以解释为什么吗?
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?
回答 0
您不能分配给类似的列表lst[i] = something
,除非该列表已至少已使用i+1
元素初始化。您需要使用append将元素添加到列表的末尾。lst.append(something)
。
(如果使用字典,则可以使用分配符号)。
创建一个空列表:
>>> l = [None] * 10
>>> l
[None, None, None, None, None, None, None, None, None, None]
为上述列表的现有元素分配一个值:
>>> l[1] = 5
>>> l
[None, 5, None, None, None, None, None, None, None, None]
请记住,类似 l[15] = 5
仍然会失败,因为我们的列表只有10个元素。
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]
使用函数创建列表:
>>> 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)
):
>>> def display():
... return [x**2 for x in range(9)]
...
>>> print display()
[0, 1, 4, 9, 16, 25, 36, 49, 64]
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]
回答 1
尝试以下方法:
lst = [None] * 10
上面将创建一个大小为10的列表,其中每个位置都初始化为None
。之后,您可以向其中添加元素:
lst = [None] * 10
for i in range(10):
lst[i] = i
诚然,这不是Python的做事方式。最好这样做:
lst = []
for i in range(10):
lst.append(i)
或更简单的一点是,在Python 2.x中,您可以执行以下操作以初始化值从0到9的列表:
lst = range(10)
在Python 3.x中:
lst = list(range(10))
Try this instead:
lst = [None] * 10
The above will create a list of size 10, where each position is initialized to 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. Better do this:
lst = []
for i in range(10):
lst.append(i)
Or even simpler, in Python 2.x you can do this to initialize a list with values from 0 to 9:
lst = range(10)
And in Python 3.x:
lst = list(range(10))
回答 2
varunl当前接受的答案
>>> l = [None] * 10
>>> l
[None, None, None, None, None, None, None, None, None, None]
对于数字等非引用类型,效果很好。不幸的是,如果您要创建列表列表,则会遇到引用错误。Python 2.7.6中的示例:
>>> a = [[]]*10
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> a[0].append(0)
>>> a
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]
>>>
如您所见,每个元素都指向相同的列表对象。为了解决这个问题,您可以创建一个将每个位置初始化为不同对象引用的方法。
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], [], [], [], [], [], [], [], [], []]
>>>
可能有一种默认的内置python方式(而不是编写函数)来执行此操作,但是我不确定它是什么。很高兴得到纠正!
编辑:这是 [ [] for _ in range(10)]
范例:
>>> [ [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]]
varunl’s currently accepted answer
>>> 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:
>>> 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. Would be happy to be corrected!
Edit: It’s [ [] 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]]
回答 3
您可以.append(element)
进入列表,例如:s1.append(i)
。您当前要执行的操作是访问s1[i]
不存在的元素()。
You can .append(element)
to the list, e.g.: s1.append(i)
. What you are currently trying to do is access an element (s1[i]
) that does not exist.
回答 4
有两种“快速”方法:
x = length_of_your_list
a = [None]*x
# or
a = [None for _ in xrange(x)]
似乎[None]*x
更快:
>>> from timeit import timeit
>>> timeit("[None]*100",number=10000)
0.023542165756225586
>>> timeit("[None for _ in xrange(100)]",number=10000)
0.07616496086120605
但是,如果您可以接受范围(例如[0,1,2,3,...,x-1]
),则range(x)
可能最快:
>>> timeit("range(100)",number=10000)
0.012513160705566406
There are two “quick” methods:
x = length_of_your_list
a = [None]*x
# or
a = [None for _ in xrange(x)]
It appears that [None]*x
is faster:
>>> from timeit import timeit
>>> timeit("[None]*100",number=10000)
0.023542165756225586
>>> timeit("[None for _ in xrange(100)]",number=10000)
0.07616496086120605
But if you are ok with a range (e.g. [0,1,2,3,...,x-1]
), then range(x)
might be fastest:
>>> timeit("range(100)",number=10000)
0.012513160705566406
回答 5
我很惊讶没有人建议使用这种简单的方法来创建一个空列表。这是一个旧线程,但仅出于完整性目的添加它。这将创建一个包含10个空列表的列表
x = [[] for i in range(10)]
I’m surprised nobody suggest this simple approach to creating a list of empty lists. This is an old thread, but just adding this for completeness. This will create a list of 10 empty lists
x = [[] for i in range(10)]
回答 6
(这是根据问题的原始版本编写的。)
我想创建一个空列表(或最好的方法)以容纳10个元素。
所有列表可以容纳任意数量的元素,仅受可用内存的限制。列表中唯一重要的“大小”是当前列表中的元素数量。
但是当我运行它时,结果是[]
print display s1
语法无效;根据您对所看到内容的描述,我认为您的意思是display(s1)
然后print s1
。为此,您必须预先定义一个全局s1
变量以传递给该函数。
呼叫display
并不会像书面那样修改您传入的列表。您的代码说:“ s1
是传递给函数的任何事物的名称;好的,现在我们要做的第一件事是完全忘记该事物,让我们s1
开始引用一个新创建的事物list
。现在我们将对其进行修改。list
”。这对您传递的值没有影响。
没有理由在此处传递值。(创建一个函数也没有真正的理由,但这并不重要。)您想“创建”某些东西,这就是函数的输出。创建您所描述的事物不需要任何信息,因此请勿传递任何信息。要获取信息,return
它。
那会给你类似的东西:
def display():
s1 = list();
for i in range(0, 9):
s1[i] = i
return s1
您将要注意的下一个问题是列表实际上仅包含9个元素,因为该range
函数跳过了终点。(作为旁注,其[]
效果与一样好list()
,并且不需要分号,它s1
是变量的较差名称,并且range
如果从0
。开始,则只需要一个参数。)因此,最后得到
def create_list():
result = list()
for i in range(10):
result[i] = i
return result
但是,这仍然没有实现。range
是不是这就是语言的一部分的方式一些神奇的关键字for
和def
是,而是它的一个功能。猜猜该函数返回什么?没错-这些整数的列表。所以整个功能都崩溃了
def create_list():
return range(10)
现在您了解了为什么我们根本不需要自己编写函数;range
已经是我们要寻找的功能。同样,尽管没有必要或没有理由“调整”列表大小。
(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.
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; based on your description of what you’re seeing, I assume you meant display(s1)
and then print s1
. For that to run, you must have previously defined a global s1
to pass into the function.
Calling display
does not modify the list you pass in, as written. 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
“. 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.
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. (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
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. 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. Although, again, there is no need or reason to “pre-size” the list.
回答 7
我感到惊讶的是,创建这些初始化列表的最简单方法不在这些答案中。只需在list
函数中使用生成器:
list(range(9))
I’m a bit surprised that the easiest way to create an initialised list is not in any of these answers. Just use a generator in the list
function:
list(range(9))
回答 8
n
使用嵌套列表推导创建尺寸二维矩阵的一种简单方法:
m = [[None for _ in range(n)] for _ in range(n)]
One simple way to create a 2D matrix of size n
using nested list comprehensions:
m = [[None for _ in range(n)] for _ in range(n)]
回答 9
这是我在python中的2D列表的代码,它将显示为no。输入的行数:
empty = []
row = int(input())
for i in range(row):
temp = list(map(int, input().split()))
empty.append(temp)
for i in empty:
for j in i:
print(j, end=' ')
print('')
Here’s my code for 2D list in python which would read no. of rows from the input :
empty = []
row = int(input())
for i in range(row):
temp = list(map(int, input().split()))
empty.append(temp)
for i in empty:
for j in i:
print(j, end=' ')
print('')
回答 10
我在寻找类似问题时遇到了这样的问题。我必须构建一个2D数组,然后用字典中的元素替换每个列表(在2D数组中)的某些元素。然后,我碰上了这个 SO问题,这帮助了我,也许这将帮助其他初学者得到解决。关键技巧是将2D数组初始化为numpy数组,然后使用array[i,j]
代替array[i][j]
。
作为参考,这是我不得不使用的代码:
nd_array = []
for i in range(30):
nd_array.append(np.zeros(shape = (32,1)))
new_array = []
for i in range(len(lines)):
new_array.append(nd_array)
new_array = np.asarray(new_array)
for i in range(len(lines)):
splits = lines[i].split(' ')
for j in range(len(splits)):
#print(new_array[i][j])
new_array[i,j] = final_embeddings[dictionary[str(splits[j])]-1].reshape(32,1)
现在我知道我们可以使用列表理解了,但是为了简单起见,我使用了一个嵌套的for循环。希望这对遇到这篇文章的其他人有所帮助。
I came across this SO question while searching for a similar problem. I had to build a 2D array and then replace some elements of each list (in 2D array) with elements from a dict.
I then came across this SO question which helped me, maybe this will help other beginners to get around.
The key trick was to initialize the 2D array as an numpy array and then using array[i,j]
instead of array[i][j]
.
For reference this is the piece of code where I had to use this :
nd_array = []
for i in range(30):
nd_array.append(np.zeros(shape = (32,1)))
new_array = []
for i in range(len(lines)):
new_array.append(nd_array)
new_array = np.asarray(new_array)
for i in range(len(lines)):
splits = lines[i].split(' ')
for j in range(len(splits)):
#print(new_array[i][j])
new_array[i,j] = final_embeddings[dictionary[str(splits[j])]-1].reshape(32,1)
Now I know we can use list comprehension but for simplicity sake I am using a nested for loop. Hope this helps others who come across this post.
回答 11
使它作为功能更可重用。
def createEmptyList(length,fill=None):
'''
return a (empty) list of a given length
Example:
print createEmptyList(3,-1)
>> [-1, -1, -1]
print createEmptyList(4)
>> [None, None, None, None]
'''
return [fill] * length
Make it more reusable as a function.
def createEmptyList(length,fill=None):
'''
return a (empty) list of a given length
Example:
print createEmptyList(3,-1)
>> [-1, -1, -1]
print createEmptyList(4)
>> [None, None, None, None]
'''
return [fill] * length
回答 12
s1 = []
for i in range(11):
s1.append(i)
print s1
要创建列表,只需使用以下方括号:“ []”
要将某些内容添加到列表中,请使用list.append()
s1 = []
for i in range(11):
s1.append(i)
print s1
To create a list, just use these brackets: “[]”
To add something to a list, use list.append()
回答 13
此代码生成一个包含10个随机数的数组。
import random
numrand=[]
for i in range(0,10):
a = random.randint(1,50)
numrand.append(a)
print(a,i)
print(numrand)
This code generates an array that contains 10 random numbers.
import random
numrand=[]
for i in range(0,10):
a = random.randint(1,50)
numrand.append(a)
print(a,i)
print(numrand)
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。