解包长度为 1 的列表中的 1 元组

发布于 2024-09-09 02:18:36 字数 245 浏览 0 评论 0原文

假设我在这样的列表中有一个元组:

>>> t = [("asdf", )]

我知道该列表始终包含一个 1 元组。目前我这样做:

>>> dummy, = t
>>> value, = dummy
>>> value
'asdf'

有没有更短、更优雅的方法来做到这一点?

Suppose I have a tuple in a list like this:

>>> t = [("asdf", )]

I know that the list always contains one 1-tuple. Currently I do this:

>>> dummy, = t
>>> value, = dummy
>>> value
'asdf'

Is there a shorter and more elegant way to do this?

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

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

发布评论

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

评论(3

魂ガ小子 2024-09-16 02:18:36

尝试

(value,), = t

它比 t[0][0] 更好,因为它还断言您的列表恰好包含 1 个元组,其中有 1 个值。

Try

(value,), = t

It's better than t[0][0] because it also asserts that your list contains exactly 1 tuple with 1 value in it.

机场等船 2024-09-16 02:18:36
>>> t = [("asdf", )]
>>> t[0][0]
'asdf'
>>> t = [("asdf", )]
>>> t[0][0]
'asdf'
世界如花海般美丽 2024-09-16 02:18:36

尝试 [(val, )] = t

In [8]: t = [("asdf", )]

In [9]: (val, ) = t

In [10]: val
Out[10]: ('asdf',)

In [11]: [(val, )] = t

In [12]: val
Out[12]: 'asdf'

我认为没有一个干净的方法来解决这个问题。

val = t[0][0] 是我最初的选择,但它看起来有点难看。

[(val, )] = t 也可以,但看起来也很难看。我想这取决于哪个更容易阅读以及您想要看起来不那么难看,valt

我喜欢Lior的想法,即解压列表和元组包含一个断言。

In [16]: t2 = [('asdf', ), ('qwerty', )]

In [17]: [(val, )] = t2
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-73a5d507863a> in <module>()
----> 1 [(val, )] = t2

ValueError: too many values to unpack

Try [(val, )] = t

In [8]: t = [("asdf", )]

In [9]: (val, ) = t

In [10]: val
Out[10]: ('asdf',)

In [11]: [(val, )] = t

In [12]: val
Out[12]: 'asdf'

I don't think there is a clean way to go about it.

val = t[0][0] is my initial choice, but it looks kind of ugly.

[(val, )] = t also works but looks ugly too. I guess it depends on which is easier to read and what you want to look less ugly, val or t

I liked Lior's idea that unpacking the list and tuple contains an assert.

In [16]: t2 = [('asdf', ), ('qwerty', )]

In [17]: [(val, )] = t2
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-73a5d507863a> in <module>()
----> 1 [(val, )] = t2

ValueError: too many values to unpack
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文