I want to create a list of lists from a list of multi-field strings and wonder if it is possible to do so in a comprehension.
Input:
inputs = ["1, foo, bar", "2, tom, jerry"] Desired output:
[[1, "foo", "bar"], [2, "tom", "jerry"]] Splitting the string in a comprehension is easy:
>>> [s.split(",") for s in inputs] [['1', ' foo', ' bar'], ['2', ' tom', ' jerry']] But I'm having trouble figuring out how to access the columns after the string has been split inside the comprehension, because it would seem to require a variable assignment. The following are not valid Python, but illustrate what I'm looking for:
[[int(x), y.strip(), z.strip() for x,y,z = s.split(",")] for s in inputs] or [[int(v[0]), v[1].strip(), v[2].strip() for v = s.split(",")] for s in inputs] Is there a way to assign variables inside a comprehension so that the output can be composed of functions of the variables? A loop is trivial, but generating a list by transforming inputs sure seems like a "comprehension-ish" task.
outputs = [] for s in inputs: x,y,z = s.split(",") outputs.append([int(x), y.strip(), z.strip()])
[['1', ' foo', ' bar'], ['2', ' tom', ' jerry']],lst[0][0]would be1,lst[0][1]would befooand so on. If you need variables, you probably need to store them as maps with keys.[ ... for x, y, z in (s.split(', ') for s in inputs)]