在Python中将列表初始化为特定长度 [英] Initialise a list to a specific length in Python

查看:199
本文介绍了在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 dicts, 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 dicts to make up your list.

这篇关于在Python中将列表初始化为特定长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆