仅从 Python 中的单元素列表中获取元素? [英] Getting only element from a single-element list in Python?

查看:23
本文介绍了仅从 Python 中的单元素列表中获取元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When a Python list is known to always contain a single item, is there a way to access it other than:

mylist[0]

您可能会问,为什么要这样做?".只有好奇心.似乎有一种替代方法可以在 Python 中做一切.

You may ask, 'Why would you want to?'. Curiosity alone. There seems to be an alternative way to do everything in 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

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

显式使用迭代器协议:

singleitem = next(iter(mylist))

破坏性流行音乐:

singleitem = mylist.pop()

负指数:

singleitem = mylist[-1]

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

Set via single iteration for (because the loop variable remains available with its last value when a loop terminates):

for singleitem in mylist: break

猖獗的疯狂:

# But also the only 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)

还有很多其他的(组合或改变上述部分,或以其他方式依赖隐式迭代),但你明白了.

There are many others (combining or varying bits of the above, or otherwise relying on implicit iteration), but you get the idea.

这篇关于仅从 Python 中的单元素列表中获取元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆