一次分配多个变量,Python [英] Assign Many Variables at Once, Python

查看:22
本文介绍了一次分配多个变量,Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更好的方法来做到这一点?

a, b, c, = "yyy", "yyy", "yyy"

明显的尝试失败

a, b, c, = "yyy"a, b, c = "yyy"*3

从技术上讲,以下是有效的,但我认为这并不直观,因为这个逻辑说 a、b 和 c 是相同的,而我想要做的只是说它们初始化为相同的值

a=b=c="yyy"

解决方案

这里不需要使用元组赋值;右侧的值是不可变的,因此您也可以共享引用:

a = b = c = 'yyy'

在我看来,这一点也不不直观,python 编译器只需要在字节码中存储一个常量,而使用元组赋值需要一个额外的元组常量:

<预><代码>>>>定义 foo():... a, b, c = 'yyy', 'yyy', 'yyy'...>>>foo.__code__.co_consts(无, 'yyy', ('yyy', 'yyy', 'yyy'))>>>定义栏():... a = b = c = 'yyy'...>>>bar.__code__.co_consts(无,'yyy')

如果右侧表达式是可变的,并且您希望 abc 具有独立的对象,请不要使用它;然后使用生成器表达式:

a, b, c = ({} for _ in range(3))

或者更好的是,不要那么懒惰,直接输入它们:

a, b, c = {}, {}, {}

你的左手作业并不是动态的.

Is there a better way to do this?

a, b, c, = "yyy", "yyy", "yyy"

Obvious attempts fails

a, b, c, = "yyy"
a, b, c = "yyy"*3

Technically, the following works, but I don't think it's intuitive as this logic says a, b, and c are the same, whereas all I'm trying to do is say they initialize as the same value

a=b=c="yyy"

解决方案

No need to use tuple assignment here; the right-hand value is immutable, so you can just as well share the reference:

a = b = c = 'yyy'

This is not unintuitive at all, in my view, and the python compiler will only need to store one constant with the bytecode, while using tuple assignment requires an additional tuple constant:

>>> def foo():
...     a, b, c = 'yyy', 'yyy', 'yyy'
... 
>>> foo.__code__.co_consts
(None, 'yyy', ('yyy', 'yyy', 'yyy'))
>>> def bar():
...     a = b = c = 'yyy'
... 
>>> bar.__code__.co_consts
(None, 'yyy')

Don't use this if the right-hand expression is mutable and you want a, b and c to have independent objects; use a generator expression then:

a, b, c = ({} for _ in range(3))

or better still, don't be so lazy and just type them out:

a, b, c = {}, {}, {}

It's not as if your left-hand assignment is dynamic.

这篇关于一次分配多个变量,Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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