初始化Python中的对象列表 [英] Initialize a list of objects in Python

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

问题描述

我想初始化一个非空的对象数组/列表-类构造函数生成数据.在C ++和Java中,我将执行以下操作:

I'm a looking to initialize an array/list of objects that are not empty -- the class constructor generates data. In C++ and Java I would do something like this:

Object lst = new Object[100];

我已经挖了,但是有没有Python的方法可以做到这一点?

I've dug around, but is there a Pythonic way to get this done?

这不像我想的那样工作(我获得了对同一对象的100个引用):

This doesn't work like I thought it would (I get 100 references to the same object):

lst = [Object()]*100

但这似乎可以按照我想要的方式工作:

But this seems to work in the way I want:

lst = [Object() for i in range(100)]

对于Java来说如此简单的事情,列表理解似乎(在智力上)像是很多"工作.

List comprehension seems (intellectually) like "a lot" of work for something that's so simple in Java.

推荐答案

没有像C ++中那样为数组的每个元素隐式调用Object()构造函数的方法(在Java中,每个元素对于引用类型,新数组的值初始化为null.

There isn't a way to implicitly call an Object() constructor for each element of an array like there is in C++ (recall that in Java, each element of a new array is initialised to null for reference types).

我想说您的列表理解方法是最Python化的:

I would say that your list comprehension method is the most Pythonic:

lst = [Object() for i in range(100)]

如果不想踩词法变量i,则Python中的惯例是将_用于其值无关紧要的虚拟变量:

If you don't want to step on the lexical variable i, then a convention in Python is to use _ for a dummy variable whose value doesn't matter:

lst = [Object() for _ in range(100)]

对于Java中类似的构造,您当然可以使用*:

For an equivalent of the similar construct in Java, you can of course use *:

lst = [None] * 100

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

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