Reputation: 2075
I'm trying to use python comprehension.
I have a list which is in the format:
name_a:surname_a
name_b:surname_b
name_c:surname_c
My code initially to split each pair in a line into its own variable was:
for lined in self.account:
a, b = line.split(':')
I tried to use this comprehension, but it didn't seem to work:
(a,b) = [line.split(':') for line in self.account]
Upvotes: 1
Views: 474
Reputation: 2365
As mentioned by @MattDMo the colons are missing in your list comprehension. If you add them, a additional problem will appear. If you print the list returned from the list comprehension, it will probably look like this:
[['name_a', 'surname_a\n'], ['name_b', 'surname_b\n'], ['name_c', 'surname_c\n']]
The problem is, that you can't assign it to two variables, because the list contains the same number of elements as lines in the file.
To get the desired result, you have to transpose the two dimensional list, for example by using zip and unpacking ('*'):
>>> with open('test_file.txt') as f:
... (a, b) = zip(*[line.split(':') for line in f])
...
>>> a
('name_a', 'name_b', 'name_c')
>>> b
('surname_a\n', 'surname_b\n', 'surname_c\n')
Upvotes: 1