Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中创建具有一定大小的空列表_Python_List - Fatal编程技术网

在Python中创建具有一定大小的空列表

在Python中创建具有一定大小的空列表,python,list,Python,List,我想创建一个可以容纳10个元素的空列表(或者其他最好的方法) 之后,我希望在该列表中指定值,例如,该列表应显示0到9: s1=list(); 对于范围(0,9)内的i: s1[i]=i 打印s1 但当我运行此代码时,它会生成一个错误,或者在另一种情况下,它只显示[](空) 有人能解释一下原因吗?你可以.append(element)到列表中,例如:s1.append(i)。您当前尝试的是访问一个不存在的元素(s1[i])。请尝试以下操作: lst = [None] * 10 >>

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

之后,我希望在该列表中指定值,例如,该列表应显示0到9:

s1=list();
对于范围(0,9)内的i:
s1[i]=i
打印s1
但当我运行此代码时,它会生成一个错误,或者在另一种情况下,它只显示
[]
(空)

有人能解释一下原因吗?

你可以
.append(element)
到列表中,例如:
s1.append(i)
。您当前尝试的是访问一个不存在的元素(
s1[i]
)。

请尝试以下操作:

lst = [None] * 10
>>> b = [{} for i in range(0, 3)]
>>> b
[{}, {}, {}]
>>> b[0]['hello'] = 6
>>> b
[{'hello': 6}, {}, {}]
>>> 
上面将创建一个大小为10的列表,其中每个位置都初始化为
None
。之后,您可以向其中添加元素:

lst = [None] * 10
for i in range(10):
    lst[i] = i
诚然,这不是蟒蛇式的做事方式。最好这样做:

lst = []
for i in range(10):
    lst.append(i)
更简单的是,在Python 2.x中,您可以这样做来初始化值为0到9的列表:

lst = range(10)
在Python 3.x中:

lst = list(range(10))

除非列表已经用至少
i+1
元素初始化,否则不能分配给类似
lst[i]=something
的列表。您需要使用append将元素添加到列表的末尾
lst.append(某物)

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

创建空列表:

>>> 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个元素

范围(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,您不需要执行所有这些操作,只需返回
range(0,9)
):

(这是根据问题的原始版本编写的。)

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

所有列表都可以容纳任意数量的元素,仅受可用内存的限制。列表中唯一重要的“大小”是当前列表中元素的数量

但当我运行它时,结果是[]

打印显示s1
语法无效;根据您对所看到内容的描述,我猜您指的是
display(s1)
,然后是
print s1
。要运行该函数,您必须事先定义一个全局
s1
,以传递到函数中

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
调用
display
不会修改您输入的列表。您的代码显示“
s1
是传递给函数的任何东西的名称;好的,现在我们要做的第一件事是完全忘记这件事,让
s1
开始引用新创建的
列表
。现在我们将修改该
列表
”。这对传入的值没有影响

没有理由在这里传递值。(也没有真正的理由创建一个函数,但这不是重点。)你想“创建”一些东西,这就是你函数的输出。创建您描述的东西不需要任何信息,因此不要传递任何信息。要获取信息,
返回它

这会给你一些类似的东西:

def display():
    s1 = list();
    for i in range(0, 9):
        s1[i] = i
    return s1
您将注意到的下一个问题是,您的列表实际上只有9个元素,因为
range
函数跳过了端点。(正如旁注,
[]
list()
一样有效,分号是不必要的,
s1
是变量的一个糟糕名称,如果从
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)

现在你明白为什么我们根本不需要自己写函数了<代码>范围
已经是我们正在寻找的功能。不过,同样地,没有必要或理由“预先确定”列表的大小。

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方法(而不是编写函数),但我不确定它是什么。很高兴被纠正

编辑:它是范围(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]]
有两种“快速”方法:

似乎
[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]
)没有问题,那么
范围(x)
可能是最快的:

>>> timeit("range(100)",number=10000)
0.012513160705566406

我很惊讶没有人建议用这种简单的方法来创建一个空列表列表。这是一个旧线程,但只是为了完整性而添加它。这将创建一个包含10个空列表的列表

x = [[] for i in range(10)]
要创建列表,只需使用以下括号:“[]”


要向列表中添加内容,请使用list.append()

以下是我在python中为2D list编写的代码,它将从输入中读取行数:

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('')

我在寻找类似的问题时遇到了这个问题。我必须构建一个2D数组,然后用dict中的元素替换每个列表中的一些元素(在2D数组中)。 然后我遇到了一个问题,这个问题对我很有帮助,也许这会帮助其他初学者。 关键技巧是将2D数组初始化为numpy数组,然后使用
array[i,j]
而不是
array[i][j]

供参考
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('')
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)
import random
numrand=[]
for i in range(0,10):
   a = random.randint(1,50)
   numrand.append(a)
   print(a,i)
print(numrand)
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
list(range(9))
m = [[None for _ in range(n)] for _ in range(n)]
>>> a = [{}] * 3
>>> a
[{}, {}, {}]
>>> a[0]['hello'] = 5
>>> a
[{'hello': 5}, {'hello': 5}, {'hello': 5}]
>>> 
>>> b = [{} for i in range(0, 3)]
>>> b
[{}, {}, {}]
>>> b[0]['hello'] = 6
>>> b
[{'hello': 6}, {}, {}]
>>> 
from collections import deque
my_deque_size_10 = deque(maxlen=10)