app*_*ver 1 python variables variable-assignment
有一个更好的方法吗?
a, b, c, = "yyy", "yyy", "yyy"
Run Code Online (Sandbox Code Playgroud)
明显的尝试失败了
a, b, c, = "yyy"
a, b, c = "yyy"*3
Run Code Online (Sandbox Code Playgroud)
从技术上讲,以下工作,但我不认为这是直观的,因为这个逻辑说a,b和c是相同的,而我想要做的就是说它们初始化为相同的值
a=b=c="yyy"
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 11
这里不需要使用元组赋值; 右边的值是不可变的,所以你也可以分享参考:
a = b = c = 'yyy'
Run Code Online (Sandbox Code Playgroud)
在我看来,这并不是不直观的,python编译器只需要用字节码存储一个常量,而使用元组赋值需要一个额外的元组常量:
>>> 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')
Run Code Online (Sandbox Code Playgroud)
如果右手表达式是可变的并且你想要a,b并且c拥有独立的对象,请不要使用它; 然后使用生成器表达式:
a, b, c = ({} for _ in range(3))
Run Code Online (Sandbox Code Playgroud)
或者更好的是,不要太懒,只需输入:
a, b, c = {}, {}, {}
Run Code Online (Sandbox Code Playgroud)
这不像你的左手任务是动态的.
>>> a, b, c = ("yyy",)*3
Run Code Online (Sandbox Code Playgroud)
在上述构建相当于a = b = c = "yyy",但需要在内存中的元组的创建,仍然a,b,c只是同一个对象的引用.
对于不同的id使用:
a, b, c = ("yyy" for _ in xrange(3))
Run Code Online (Sandbox Code Playgroud)
这对于字符串无关紧要,因为它们是不可变的,但对于可变对象,它们是不同类型的赋值.
>>> a = b = c = [] #all of them are references to the same object
>>> a is b
True
>>> a.append(1) #Modifying one of them in-place affects others as well
>>> a, b, c
([1], [1], [1])
>>> a, b, c, = ([],)*3 #same as a = b = c = []
>>> a is b
True
#Here a, b, c point to different objects
>>> a, b, c, = ([] for _ in xrange(3))
>>> a is b
False
>>> a.append(1)
>>> a, b, c
([1], [], [])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
202 次 |
| 最近记录: |