Unpacking a 1-tuple in a list of length 1
Suppose I hav开发者_开发问答e 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?
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.
>>> t = [("asdf", )]
>>> t[0][0]
'asdf'
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
精彩评论