解包长度为 1 的列表中的 1 元组
假设我在这样的列表中有一个元组:
>>> 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试
它比
t[0][0]
更好,因为它还断言您的列表恰好包含 1 个元组,其中有 1 个值。Try
It's better than
t[0][0]
because it also asserts that your list contains exactly 1 tuple with 1 value in it.尝试
[(val, )] = t
我认为没有一个干净的方法来解决这个问题。
val = t[0][0]
是我最初的选择,但它看起来有点难看。[(val, )] = t
也可以,但看起来也很难看。我想这取决于哪个更容易阅读以及您想要看起来不那么难看,val
或t
我喜欢Lior的想法,即解压列表和元组包含一个断言。
Try
[(val, )] = t
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
ort
I liked Lior's idea that unpacking the list and tuple contains an assert.