在Python中预先初始化列表内容和长度的实现
作者:lyshello123 时间:2022-03-17 04:30:37
如果想设置相同的初值和想要的长度
>>> a=[None]*4
>>> print(a)
[None, None, None, None]
如果我们预先知道列表的长度,那预先初始化该长度的列表,然后对每一个赋值,会比每次list.append()更有效率。
如果想要序列初值,可以用range函数,但注意,range函数返回的是可迭代对象,需要转化成list
>>> b=list(range(10))
>>> print(b)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b=range(10)
>>> print(b)
range(0, 10)
如果想剔除掉不想要的数据,可以用列表推导式
>>> c=[i for i in range(10) if i%2==0 and i<8]
>>> print(c)
[0, 2, 4, 6]
来源:https://blog.csdn.net/songyunli1111/article/details/79476983
标签:Python,初始化,列表内容,长度
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
ASP 精华源码收集(五年总结)第1/20页
2011-04-07 11:15:00
人性化网页设计技巧
2007-10-15 13:02:00
Golang TCP粘包拆包问题的解决方法
2023-07-18 11:04:43
python中迭代器(iterator)用法实例分析
2023-12-16 05:32:51
PHP实现的AES双向加密解密功能示例【128位】
2023-09-30 14:52:51
python基础教程之分支、循环简单用法
2021-05-30 08:51:48
分类与类型的问题
2008-09-12 13:10:00
![](https://img.aspxhome.com/file/UploadPic/20089/12/2008912131610841s.jpg)
FrontPage2002简明教程五:css样式表的应用
2008-09-17 11:31:00
![](https://img.aspxhome.com/file/UploadPic/200810/17/20081017113345609s.jpg)
Python cookbook(数据结构与算法)找出序列中出现次数最多的元素算法示例
2021-04-16 10:50:05
python利用json和pyecharts画折线图实例代码
2022-05-02 14:56:19
![](https://img.aspxhome.com/file/2023/1/71441_0s.jpg)
服务端XMLHTTP(ServerXMLHTTP in ASP)进阶应用-User Agent伪装
2008-11-11 12:29:00
![](https://img.aspxhome.com/file/UploadPic/200811/11/if8l_googlerss-96s.png)
解决在Dreamweaver中不支持中文文件名的方法
2010-09-02 12:35:00
清理你的CSS
2009-10-06 15:11:00
![](https://img.aspxhome.com/file/UploadPic/200910/6/dust-60s.jpg)
python使用pyaudio录音和格式转化方式
2023-11-07 19:30:03
新功能的帮助与破坏
2010-01-17 10:15:00
![](https://img.aspxhome.com/file/UploadPic/20101/17/bai_photo-14s.png)
Python利用matplotlib.pyplot绘图时如何设置坐标轴刻度
2023-09-18 23:32:01
![](https://img.aspxhome.com/file/2023/5/62895_0s.png)
Python爬虫基础之爬虫的分类知识总结
2021-12-24 03:20:12
![](https://img.aspxhome.com/file/2023/4/71464_0s.png)
linux安装Python3.4.2的操作方法
2022-06-17 19:19:15
asp如何直接调用后台存储过程?
2010-06-28 18:27:00
很酷的JQuery Solar System
2007-12-15 08:09:00
![](https://img.aspxhome.com/file/UploadPic/200712/15/200712158138849s.png)