在 Python 中仅从单元素列表中获取元素?
- 2025-02-27 09:07:00
- admin 原创
- 57
问题描述:
当已知 Python 列表始终包含单个项目时,除了以下方法之外,还有其他方法可以访问它吗:
mylist[0]
你可能会问,“你为什么要这么做?” 只是好奇而已。似乎还有另一种方法可以用 Python完成所有事情。
解决方案 1:
如果不是正好一个项目,则会引发异常:
序列解包:
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
还有许多其他方法(组合或改变上述内容,或依赖于隐式迭代),但你明白了。
解决方案 2:
我要补充的是,该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
解决方案 3:
(这是我对与集合相关的类似问题的回答的调整后的转发。)
一种方法是使用reduce
with 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 滥用”(参见评论)。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD