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 the problem I am trying to solve is, I have the string:
a = "1;2;4
3;4;5"
And I would like to perform this:
>>> [(x.split(";")[1],x.split(";")[2]) for x in a.split("
") if x.split(",")[1] != 5]
[('2', '4'), ('4', '5')]
Without the need for running split three times. So something like this (Which is obviously invalid syntax but hopefully is enough to get the message across):
[(x[1],x[2]) for x.split(";") in a.split("
") if x[1] != 5]
In this question I am not looking for fancy ways to get the 2nd and 3rd column of the string. It is just a way of providing a concrete example. I could for course for the example use:
[x.split(";")[1:3] for x in a.split("
")]
The possible solutions I have thought of:
- Not use a list comprehension
- Leave it as is
- Use the
csv.DictReader
, name my columns and something like StringIO
to give it the input.
This is mostly something that would be a nice pattern to be able to use rather than a specific case so its hard to answer the "why do you want to do this" or "what is this for" kind of questions
Update: After being reading the solution below I went and ran some speed tests. And I found in my very basic tests that the solution provided was 35% faster than the naive solution above.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…