星号运算符 (*) 应用于列表和整数 [英] Star operator (*) applied to lists and integers

查看:45
本文介绍了星号运算符 (*) 应用于列表和整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个 Foo 类,我们想实例化一个 foos 列表,我们可以这样做:

Let's say we have a Foo class and we want to instantiate a lists of foos, which we can do as follows:

foo_list = [Foo()] * 3

现在如果我们执行 foo_list[0].x = 5 会怎样?此语句会将属性x 设置为所有 列表中的实例!!!

Now what if we do foo_list[0].x = 5? This statement will set the attribute x to all of the instances inside the list!!!

当我发现它时,它让我大吃一惊.问题是,当我们创建这样的列表时,显然 python 将首先创建 Foo 实例,然后是列表实例,然后将相同的对象附加到它 3 次,但我真的希望它做这样的事情:

When I found this it blew my mind. The problem is that when we create a list like that, apparently python will create the Foo instance first, then the list instance, and then append the same object to it 3 times, but I really would expect it to do something like this:

foo_list = [Foo() for i in range(3)]

你不也是吗?好吧,现在我知道这个语法糖绝对不能像我想用的那样使用,但是,它有什么用呢?我唯一能想到的就是创建一个初始大小如下的列表:list = [None] * 5,这在 python 的情况下对我来说没有多大意义.

Wouldn't you too? Well, now I know that definitely this syntactic sugar can't be used as I wanted to use it, but then, what is it used for? The only thing I can think of is to create a list with an initial size like this: list = [None] * 5, and that doesn't make much sense to me in the case of python.

这个语法还有其他真正有用的用例吗?

Does this syntax have any other really useful use case?

推荐答案

你可以使用星形形式,任何不可变类型,像这样

You can use the star form, with any immutable type, like this

print [5] * 3
print "abc" * 3
print [1.1] * 3
print (8,) * 3

比方说,例如

nums = [5] * 3
print map(id, nums)

在我的机器上输出

[41266184, 41266184, 41266184]

id 函数给出了一个唯一的当前对象的id.如您所见,以这种方式创建不可变对象非常简单且高效.因为创建的对象中的所有元素,都指向同一个元素.(记住使用的对象是不可变的)

id function gives a unique id of the current object. As you can see, creating immutable objects this way is very simple, and efficient. Because all the elements in the created object, point to the same element. (Remember the objects used are immutable)

因此,作为经验法则

如果对象是可变的,使用列表理解形式

if the objects are mutable, use list comprehension form

[Foo() for i in range(3)]

如果对象不可变,可以使用星型

if the objects are immutable, use can use the star form

[5] * 3

这篇关于星号运算符 (*) 应用于列表和整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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