Reputation: 25629
How do I use list comprehension for doing this:
MCs= [['foo', 180.9], ['bar', 163.5], ['noo', 140.3]]
Want
[['foo'], ['bar'], ['noo']]
using
MCs = [list(x[0]) for x in MCs
]
I get this:
[['f', 'o', 'o'], ['b', 'a', 'r'], ['n', 'o', 'o']]
Upvotes: 1
Views: 236
Reputation: 612804
To get precisely what you ask for do this:
>>> [[x[0]] for x in MCs]
[['foo'], ['bar'], ['noo']]
But perhaps what you really want is this:
>>> [x[0] for x in MCs]
['foo', 'bar', 'noo']
Upvotes: 1
Reputation: 17721
Try this for your answer.
[[x[0],] for x in MCs]
So dissecting what your list comprehension:
for x in [['foo', 180.9], ['bar', 163.5], ['noo', 140.3]]:
# x = ['foo', 180.9] first time through
# x[0] = 'foo'
# list(x[0]) = ['f','o','o']
Upvotes: 1
Reputation:
That's because x[0]
is e.g. 'foo'
and list
turns an iterable into a list containing the items of the iterable - iterating a string yields its characters one at a time. It's unrelated to the list comprehension, the same thing would happen if you used list('foo')
. To make a singleton list, just wrap the expression in square brackes, i.e. [[mc[0]] for mc in mcs]
.
Upvotes: 5
Reputation: 129764
You only need this:
MCs = [[x[0]] for x in MCs]
Strings are iterable, and list(iterable)
returns a list of elements yielded by the argument (i.e. characters, in this case).
Upvotes: 6
Reputation: 391286
Use this:
[[x[0]] for x in MCs]
list(c)
takes a collection of something and makes it into a list. A string is a collection of characters, so that's what you get, a list of characters.
Upvotes: 3