Merlin
Merlin

Reputation: 25629

How to use list comprehension in python?

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

Answers (6)

riza
riza

Reputation: 17114

Using zip:

[[x] for x in zip(*MCs)[0]]

Upvotes: 0

David Heffernan
David Heffernan

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

dr jimbob
dr jimbob

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

user395760
user395760

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

Cat Plus Plus
Cat Plus Plus

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

Lasse V. Karlsen
Lasse V. Karlsen

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

Related Questions