2011-04-27 3 views
78

非常に長いリストの理解度をどのように分割するのですか?リストの補完やジェネレータの式をPythonで続ける

[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long] 

私はまた、行を分割するために「\」を使用して嫌いの人、 しかし、なぜ理解していなかったことをどこかで見てきました。これの背後にある理由は何ですか?

+3

[インデントのPythonのリスト内包する方法?](http://stackoverflow.com/questions/311588/how-to-indent-python-list-comprehensions) –

答えて

107
[x 
for 
x 
in 
(1,2,3) 
] 

は、うまく動作しますので、しばらくお待ちください。私は個人的に\が非常に高く評価されていない理由は、それが持っている、それが目立つか、余分なパディングを必要としないのいずれかのライン、の最後に見えることである

[something_that_is_pretty_long 
    for something_that_is_pretty_long 
    in somethings_that_are_pretty_long] 

を好みます行が変更長時に固定される。このような場合には

x = very_long_term      \ 
    + even_longer_term_than_the_previous \ 
    + a_third_term 

、使用は括弧:私はに反対していないよ

x = (very_long_term 
    + even_longer_term_than_the_previous 
    + a_third_term) 
+34

特に、改行は内部で無視されます*任意の*かっこ - '()'、 '[]'と '{}'。 – delnan

17

を:

variable = [something_that_is_pretty_long 
      for something_that_is_pretty_long 
      in somethings_that_are_pretty_long] 

この場合、\は必要ありません。一般に、私は人々が\を避けていると思うのですが、それはちょっと醜いですが、行の最後のものでなければ問題を引き起こす可能性があります(空白がないことを確認してください)。しかし、あなたの行の長さを抑えるために、それを使用する方がずっと優れていると思います。

上記の場合には\は必要ないため、かっこ式の場合は、実際に使用する必要があることは非常にまれです。

16

複数のデータ構造のリストを扱う場合には、複数のインデントを使用することもできます。

new_list = [ 
    { 
     'attribute 1': a_very_long_item.attribute1, 
     'attribute 2': a_very_long_item.attribute2, 
     'list_attribute': [ 
      { 
       'dict_key_1': attribute_item.attribute2, 
       'dict_key_2': attribute_item.attribute2 
      } 
      for attribute_item 
      in a_very_long_item.list_of_items 
     ] 
    } 
    for a_very_long_item 
    in a_very_long_list 
    if a_very_long_item not in [some_other_long_item 
     for some_other_long_item 
     in some_other_long_list 
    ] 
] 

if文を使用して別のリストにフィルタする方法にも注意してください。 if文をそれ自身の行にドロップすると便利です。

関連する問題