简体   繁体   English

当期望列表仅包含单个元素时,获取列表元素的Python方法?

[英]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.

相关问题 Pythonic方式获取1个大小的列表的单个元素 - Pythonic way to get the single element of a 1-sized list 检查列表中的元素是否包含在密钥字典中的Python方法 - Pythonic way to check if element in a list contains in key dictionary 一种删除列表中仅一个元素的连续重复项的pythonic方法 - A pythonic way to delete successive duplicates of only one element in a list 如果满足条件,修改列表元素的Python方法 - Pythonic way to modify list element if condition is met 如果在列表元素中找到某个字符,则返回列表元素的Python方法 - Pythonic way of returning an element of a list if a certain char is found in that element 确保对象列表的大多数pythonic方法仅包含唯一项 - Most pythonic way of ensuring a list of objects contains only unique items 从多个列表中的字典列表中获取元素索引的Python方法 - Pythonic way to get the index of element from a list of dicts depending on multiple keys Pythonic方法检查条件是否适用于列表的任何元素 - Pythonic way of checking if a condition holds for any element of a list 一种在不生成新列表的情况下删除元素的所有实例的pythonic方法 - A pythonic way to remove all instances of an element without generating a new list 在条件列表中随机选择元素的大多数Python方法 - Most pythonic way to select at random an element in a list with conditions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM