[英]Pythonic way to get list element when expectation is that list contains only a single element?
I often run into the situation where I am querying some data source that returns a list, however I'm expecting the list to contain only a single element. 我经常遇到查询返回列表的数据源的情况,但是我期望列表仅包含一个元素。 Right now I do:
现在,我这样做:
el = result_list[0]
maybe in a try block in case the list is empty. 可能在try块中,以防列表为空。 But, I don't like it.
但是,我不喜欢它。 What is the best way?
什么是最好的方法? It would be cool to do this:
这样做很酷:
el = result_list.only()
And perhaps that could puke if the list is empty or has more than one element. 如果列表为空或具有多个元素,则可能会呕吐。
In Python 2 or 3: 在Python 2或3中:
>>> a, = [1]
>>> a
1
>>> a, = []
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 0 values to unpack
>>> a, = [1,2,3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 1)
In Python 3, you can also 在Python 3中,您还可以
>>> a,*_ = [1,2,3]
>>> a
1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.