0

我想将python代码分成两行,我的代码类似于:

if long_named_three_d_array[first_dimension][second_dimension][third_dimension] == somevalue:
    //dosomething

如果条件超过两行,我想在上面拆分。

请帮忙。谢谢。

4

3 回答 3

5

在 Python 中,LHS 可以用括号括起来。

>>> a = {}
>>> a[1] = {}
>>> a[1][2] = {}
>>> (a[1][2]
... [3]) = ''
>>> a
{1: {2: {3: ''}}}
>>> (b) = 2
>>> b
2

这意味着您可以将您的行写为

if (long_named_three_d_array[first_dimension] 
    [second_dimension]
    [third_dimension] ) == somevalue:
# Rest of code here, obviously properly indented in for the if.
于 2012-04-10T02:27:41.093 回答
1

您可以使用换行符继续字符\.

if long_named_three_d_array[first_dimension] \
    [second_dimension]\
    [third_dimension] == somevalue:
# Rest of code here, obviously properly indented in for the if.
于 2012-04-10T02:30:14.483 回答
1

一种方法是使用临时变量:

tmp = long_named_three_d_array[first_dimension][second_dimension][third_dimension] 
if tmp == somevalue:
    //dosomething

如果可能的话,虽然更短但描述性的变量标识符将是一个更好的选择。

于 2012-04-10T02:36:45.527 回答