如何在Python中将列表初始化为特定值 [英] How to initialize a list to a certain value in Python

查看:321
本文介绍了如何在Python中将列表初始化为特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得一个列表,其中每个项目均设置为某个值(在我的情况下为0).我已经用下面的代码在代码中解决了这个问题,但是感觉很混乱.当然有更好的方法了吗?

I'd like to get a list where each item is set to a certain value (in my case, 0). I've solved this in my code with the code below, but it feels so messy. Surely there's a better way?

maxWidths = map(lambda x: 0, range(0, maxCols))

推荐答案

将一个元素列表乘以所需的长度.

Multiply a one-element list by the desired length.

maxWidths = [0] * maxCols


在上面,列表的所有元素都是相同的对象. 如果您要创建可变值的列表(例如字典或列表),并且需要将它们与众不同,则可以像在问题中一样使用map,或编写等效的列表理解:


In the above, all elements of the list will be the same objects. In case you're be creating a list of mutable values (such as dicts or lists), and you need them to be distinct, you can either use map as you did in the question, or write an equivalent list comprehension:

[[] for dummy in range(100)]

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

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