List comprehensions splitting loop variable

后端 未结 2 556
北海茫月
北海茫月 2021-01-07 18:37

I am trying to find out if there is a way to split the value of each iteration of a list comprehension only once but use it twice in the output.

As an example of th

2条回答
  •  孤街浪徒
    2021-01-07 19:23

    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 5; and thus re-use parts to produce the mapped value:

    # text = '1;2;4\n3;4;5'
    [(parts[1], parts[2]) for line in text.split('\n') if (parts := line.split(';'))[1] != 5]
    # [('2', '4'), ('4', '5')]
    

提交回复
热议问题