在Python中将列表初始化为特定长度 [英] Initialise a list to a specific length in Python
问题描述
如何在Python中使用默认值的10倍初始化列表?
How do I initialise a list with 10 times a default value in Python?
我正在寻找一种美观的方法来初始化具有特定范围的空列表. 因此,请创建一个包含10个零或类似内容的列表,以确保我的列表具有特定的长度.
I'm searching for a good-looking way to initialize a empty list with a specific range. So make a list that contains 10 zeros or something to be sure that my list has a specific length.
推荐答案
如果您想要的默认值"是不可变的,例如@eduffy的建议. [0]*10
,足够好.
If the "default value" you want is immutable, @eduffy's suggestion, e.g. [0]*10
, is good enough.
但是,如果您想要列出十个dict
的列表,请不使用[{}]*10
-这会给您一个列表,相同最初为空的dict
十次,不十个不同.而是使用[{} for i in range(10)]
或类似的构造来构造十个单独的dict
来组成您的列表.
But if you want, say, a list of ten dict
s, do not use [{}]*10
-- that would give you a list with the same initially-empty dict
ten times, not ten distinct ones. Rather, use [{} for i in range(10)]
or similar constructs, to construct ten separate dict
s to make up your list.
这篇关于在Python中将列表初始化为特定长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!