python生成指定长度的列表,如何在python中创建固定大小列表?

在Python中,可以通过多种方式创建固定大小的列表,如使用`[None]*10`或者`[None for _ in range(10)]`。虽然这些方法会预先填充元素,但如果你想要未初始化的内存效果,可以使用numpy的`numpy.empty`或`numpy.empty_like`。对于性能比较,在Python 2和3中,`[None]*10000`通常是最快的选择,但在处理元素时,这种优化可能并不重要。
摘要由CSDN通过智能技术生成

In C++, I can create a array like...

int* a = new int[10];

in python,I just know that I can declare a list,than append some items,or like..

l = [1,2,3,4]

l = range(10)

Can I initialize a list by a given size,like c++,and do not do any assignment?

解决方案

(tl;dr: The exact answer to your question is numpy.empty or numpy.empty_like, but you likely don't care and can get away with using myList = [None]*10000.)

Simple methods

You can initialize your list to all the same element. Whether it semantically makes sense to use a non-numeric value (that will give an error later if you use it, which is a good thing) or something like 0 (unusual? maybe useful if you're writing a sparse matrix or the 'default' value should be 0 and you're not worried about bugs) is up to you:

>>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值