开发者

Stripping characters from tuples in a list

I have a list of tuples in this form (generated by a DB query):

[(280.73,), (281.359,), (280.630,)]

I would like to remove the () and c开发者_如何转开发ommas to achieve something like this, making it more compatible to form into a JSON.

[280.73,281.359,280.630]

What is the easiest way to do this?


Given a list of single-element tuples (let's call it l (for list)). You want to flatten this into a list of elements.

A list comprehension, extracting the first element of each tuple will do the job:

>>> l = [(280.73,), (281.359,), (280.630,)]
>>> [t[0] for t in l]
[280.73000000000002, 281.35899999999998, 280.63]
>>> 


The easiest is probably through list comprehension:

cleaned = [i[0] for i in [(280.73,), (281.359,), (280.630,)]]


These examples will work with arbitrary elements number of tuples.

>>> l = [(280.73,), (281.359,), (280.630,)]
>>> [ v for b in l for v in b ]
[280.73, 281.359, 280.63]
>>> from itertools import chain
>>> list(chain(*l))
[280.73, 281.359, 280.63]
>>> 


Just as an alternative hack, you can do this as well:

>>> stuff = [(280.73,), (281.359,), (280.630,)]
>>> sum(stuff, ())
(280.73, 281.359, 280.63)

To convert it to a list, pass it into the list function:

>>> stuff = [(280.73,), (281.359,), (280.630,)]
>>> list(sum(stuff, ()))
[280.73, 281.359, 280.63]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜