python – multiple variables in list comprehension?

python – multiple variables in list comprehension?

You can do this with two for clauses in your list comprehension. The first iterates over the items in the list. The second iterates over a single-item list containing the list derived from splitting the string (which is needed so we can unpack this into three separate variables).

[[int(x), y.strip(), z.strip()] for s in inputs for (x, y, z) in [s.split(,)]]

The for clauses go in a somewhat counterintuitive order, but it matches the way youd write it as nested for loops.

Jon Sharpes use of a nested comprehension (generator expression, actually) is similar and probably clearer. The use of multiple for clauses always seems confusing to me; mainly I wanted to see if I could make use of it here.

Thanks for all the suggestions – its great to see the variety of possible techniques, as well as a counterexample to the zen of Pythons There should be one — and preferably only one — obvious way to do it.

All 4 solutions are equally beautiful, so its a bit unfair to have to give the coveted green check to only one of them. I agree with the recommendations that #1 is the cleanest and best approach. #2 is also straightforward to understand, but having to use a lambda inside a comprehension seems a bit off. #3 is nice in creating an iterator with map but gets a tiny demerit for needing the extra step of iterating over it. #4 is cool for pointing out that nested fors are possible — if I can remember that they go in first, second order instead of inner, outer. Since #1 is not in the form of an answer, #4 gets the check for most surprising.

Thanks again to all.

inputs = [1, foo, bar, 2,tom,  jerry]

outputs1 = [[int(x), y.strip(), z.strip()] for x,y,z in (s.split(,) for s in inputs)]
print(1:, outputs1)       # jonrsharpe

outputs2 = [(lambda x, y, z: [int(x), y.strip(), z.strip()])(*s.split(,)) for s in inputs]
print(2:, outputs2)       # yper

outputs3 = [z for z in map(lambda x: [int(x[0]), x[1].strip(), x[2].strip()],[s.split(,) for s in inputs])]
print(3:, outputs3)       # user2314737

outputs4 = [[int(x), y.strip(), z.strip()] for s in inputs for (x, y, z) in [s.split(,)]]
print(4:, outputs4)       # kindall

Results:

1: [[1, foo, bar], [2, tom, jerry]]
2: [[1, foo, bar], [2, tom, jerry]]
3: [[1, foo, bar], [2, tom, jerry]]
4: [[1, foo, bar], [2, tom, jerry]]

python – multiple variables in list comprehension?

If you really want to do it in one line, you can do something like this, although its not the clearest code (first line is the code, second line is the output).

>>> [(lambda x, y, z: [int(x), y.strip(), z.strip()])(*s.split(,)) for s in inputs]
[[1, foo, bar], [2, tom, jerry]]

Or this.

>>> [(lambda x: [int(x[0]), x[1].strip(), x[2].strip()])(s.split(,)) for s in inputs]
[[1, foo, bar], [2, tom, jerry]

Edit:
See jonrsharpes comment for the best answer IMHO.

Leave a Reply

Your email address will not be published.