List comprehensions splitting loop variable

后端 未结 2 539
北海茫月
北海茫月 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:19

    You could use a list comprehension wrapped around a generator expression:

    [(x[1],x[2]) for x in (x.split(";") for x in a.split("\n")) if x[1] != 5]
    
    0 讨论(0)
  • 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')]
    
    0 讨论(0)
提交回复
热议问题