Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

python - List comprehensions splitting loop variable

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:

  1. Not use a list comprehension
  2. Leave it as is
  3. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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("
")) if x[1] != 5]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...