一个更简单的解决方案是使用元组解包.这已经做了你想要的一切,包括检查它只包含一个项目.
单项:
>>> name, = (name for name in ('bob','fred') if name=='bob') >>> name 'bob'
过多的物品:
>>> name, = (name for name in ('bob','bob') if name=='bob') Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack
没有相关产品:
>>> name, = (name for name in ('fred','joe') if name=='bob') Traceback (most recent call last): File "", line 1, in ValueError: need more than 0 values to unpack