用于跨多行分配多个变量的 Python 语法

我试图在一个语句中为多个变量赋值,但我不知道是否有一种很好的语法可以将它拆分为多行。


# This is the long version I don't want

a, b, c, d = tf.constant(1, name='constant_a'), tf.constant(2, name='constant_b'), tf.constant(3, name='constant_c'), tf.constant(4, name='constant_d')


# Does something like this exist?

a, b, c, d = tf.constant(1, name='constant_a'), /

             tf.constant(2, name='constant_b'), /

             tf.constant(3, name='constant_c'), /

             tf.constant(4, name='constant_d')

有没有一种不错的 Pythonic 方式来做到这一点?


蝴蝶刀刀
浏览 118回答 3
3回答

潇潇雨雨

我认为您正在考虑反斜杠(续行)。a, b, c, d = tf.constant(1, name='constant_a'), \              tf.constant(2, name='constant_b'), \              tf.constant(3, name='constant_c'), \              tf.constant(4, name='constant_d')这有效,但它很丑。最好使用Joseph 的回答中的元组/列表,或者更好的是Josh 的回答中的理解。

aluckdog

不确定它是否更具可读性/Pythonic,但这是最简洁的!a, b, c, d = [tf.constant(i, name='constant_' + x) for i, x in zip(range(1, 5), 'abcd')]

largeQ

把你有的东西放在括号里。a, b, c, d = (tf.constant(1, name='constant_a'),                tf.constant(2, name='constant_b'),                tf.constant(3, name='constant_c'),               tf.constant(4, name='constant_d'))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python