仅从 Python 中的单元素列表中获取元素?

Getting only element from a single-element list in Python?

当已知 Python 列表始终包含单个项目时,是否有其他方法访问它:

mylist[0]

你可能会问,'Why would you want to?'。一个人的好奇心。似乎有另一种方法可以在 Python.

中完成 一切

如果不恰好一项则引发异常:

序列解包:

singleitem, = mylist
# Identical in behavior (byte code produced is the same),
# but arguably more readable since a lone trailing comma could be missed:
[singleitem] = mylist

疯狂疯狂,将输入解包到身份lambda函数:

# The only even semi-reasonable way to retrieve a single item and raise an exception on
# failure for too many, not just too few, elements as an expression, rather than a
# statement, without resorting to defining/importing functions elsewhere to do the work
singleitem = (lambda x: x)(*mylist)

所有其他人默默地忽略规范违规,生产第一个或最后一个项目:

明确使用迭代器协议:

singleitem = next(iter(mylist))

破坏性流行:

singleitem = mylist.pop()

负指数:

singleitem = mylist[-1]

通过单次迭代设置for(因为循环终止时循环变量及其最后一个值仍然可用):

for singleitem in mylist: break

还有很多其他的(组合或改变上面的位,或者以其他方式依赖隐式迭代),但你明白了。

我要补充的是 more_itertools 图书馆有一个工具,returns 一个可迭代的项目。

from more_itertools import one


iterable = ["foo"]
one(iterable)
# "foo"

此外,more_itertools.one 如果 iterable 为空或有多个项目,则会引发错误。

iterable = []
one(iterable)
# ValueError: not enough values to unpack (expected 1, got 0)

iterable = ["foo", "bar"]
one(iterable)
# ValueError: too many values to unpack (expected 1)

more_itertools是第三方包> pip install more-itertools

(这是 my answer 对与集合相关的类似问题的调整后转发。)

一种方法是将 reducelambda x: x 结合使用。

from functools import reduce

> reduce(lambda x: x, [3]})
3

> reduce(lambda x: x, [1, 2, 3])
TypeError: <lambda>() takes 1 positional argument but 2 were given

> reduce(lambda x: x, [])
TypeError: reduce() of empty sequence with no initial value

好处:

  • 多个值和零值失败
  • 不改变原来的列表
  • 不需要新变量,可以作为参数传递

缺点:“API 滥用”(见评论)。