Unpacking a 1-tuple in a list of length 1

☆樱花仙子☆ 提交于 2019-12-08 16:27:23

问题


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?


回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/3219573/unpacking-a-1-tuple-in-a-list-of-length-1

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