当已知 Python 列表始终包含单个项目时,是否有其他方法可以访问它:
mylist[0]
您可能会问,“您为什么想要这样做?”。唯有好奇心。似乎有一种替代方法可以在 Python 中完成一切。
[singleitem] = mylist
# Identical in behavior (byte code produced is the same),
# but arguably less 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
库有一个工具可以从可迭代对象中返回一项。
from more_itertools import one
iterable = ["foo"]
one(iterable)
# "foo"
more_itertools.one
会引发错误。
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
(这是对与集合相关的类似问题的我的回答的调整后的重新发布。)
一种方法是将
reduce
与 lambda 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 滥用”(见评论)。