Temporary variable within list comprehension

后端 未结 3 2148
[愿得一人]
[愿得一人] 2021-02-19 05:07

It happens to me quite often to have a piece of code that looks like this.

raw_data  = [(s.split(\',\')[0], s.split(\',\')[1]) for s in all_lines if s.split(\',         


        
3条回答
  •  既然无缘
    2021-02-19 05:29

    Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), it's possible to use a local variable within a list comprehension in order to avoid calling twice the same expression:

    In our case, we can name the evaluation of line.split(',') as a variable parts while using the result of the expression to filter the list if parts[1] is not equal to NaN; and thus re-use parts to produce the mapped value:

    # lines = ['1,2,3,4', '5,NaN,7,8']
    [(parts[0], parts[1]) for line in lines if (parts := line.split(','))[1] != 'NaN']
    # [('1', '2')]
    

提交回复
热议问题