从列表中的元组中删除字符

发布于 2024-12-09 00:52:34 字数 210 浏览 2 评论 0原文

我有一个这种形式的元组列表(由数据库查询生成):

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

我想删除 () 和逗号来实现类似的功能,使其更兼容形成 JSON。

[280.73,281.359,280.630]

做到这一点最简单的方法是什么?

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 commas 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

浅唱ヾ落雨殇 2024-12-16 00:52:34

给定一个单元素 元组列表(我们称之为l(对于list))。您想将其展平为元素列表。

列表理解,提取每个元组的第一个元素将完成这项工作:

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

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]
>>> 
初懵 2024-12-16 00:52:34

最简单的可能是通过列表理解:

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

The easiest is probably through list comprehension:

cleaned = [i[0] for i in [(280.73,), (281.359,), (280.630,)]]
夜声 2024-12-16 00:52:34

这些示例将适用于任意元素数量的元组。

>>> 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]
>>> 

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]
>>> 
半﹌身腐败 2024-12-16 00:52:34

作为一种替代方法,您也可以这样做:

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

要将其转换为列表,请将其传递到 list 函数中:

>>> stuff = [(280.73,), (281.359,), (280.630,)]
>>> list(sum(stuff, ()))
[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]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文