Python list of tuples to list of int

落爺英雄遲暮 提交于 2019-12-05 01:22:42

You didn't say what you mean by "best", but presumably you mean "most pythonic" or "most readable" or something like that.

The list comprehension given by F3AR3DLEGEND is probably the simplest. Anyone who knows how to read a list comprehension will immediately know what it means.

y = [i[0] for i in x]

However, often you don't really need a list, just something that can be iterated over once. If you've got a billion elements in x, building a billion-element y just to iterate over it one element at a time may be a bad idea. So, you can use a generator expression:

y = (i[0] for i in x)

If you prefer functional programming, you might prefer to use map. The downside of map is that you have to pass it a function, not just an expression, which means you either need to use a lambda function, or itemgetter:

y = map(operator.itemgetter(0), x)

In Python 3, this is equivalent to the generator expression; if you want a list, pass it to list. In Python 2, it returns a list; if you want an iterator, use itertools.imap instead of map.

If you want a more generic flattening solution, you can write one yourself, but it's always worth looking at itertools for generic solutions of this kind, and there is in fact a recipe called flatten that's used to "Flatten one level of nesting". So, copy and paste that into your code (or pip install more-itertools) and you can just do this:

y = flatten(x)

If you look at how flatten is implemented, and then at how chain.from_iterable is implemented, and then at how chain is implemented, you'll notice that you could write the same thing in terms of builtins. But why bother, when flatten is going to be more readable and obvious?

Finally, if you want to reduce the generic version to a nested list comprehension (or generator expression, of course):

y = [j for i in x for j in i]

However, nested list comprehensions are very easy to get wrong, both in writing and reading. (Note that F3AR3DLEGEND, the same person who gave the simplest answer first, also gave a nested comprehension and got it wrong. If he can't pull it off, are you sure you want to try?) For really simple cases, they're not too bad, but still, I think flatten is a lot easier to read.

y = [i[0] for i in x]

This only works for one element per tuple, though.

However, if you have multiple elements per tuple, you can use a slightly more complex list comprehension:

y = [i[j] for i in x for j in range(len(i))]

Reference: List Comprehensions

Just do this:

x = [i[0] for i in x]

Explanation:

>>> x=[(12,), (1,), (3,)]

>>> x
[(12,), (1,), (3,)]

>>> [i for i in x]
[(12,), (1,), (3,)]

>>> [i[0] for i in x]
[12, 1, 3]

This is the most efficient way:

x = [i for i, in x]

or, equivalently

x = [i for (i,) in x]

This is a bit slower:

x = [i[0] for i in x]

you can use map function....

map(lambda y: y[0], x)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!