栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

你不能分配给类似的列表

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]


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/402312.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号