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

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

问题描述

当已知Python列表始终包含单个项目时,除了以下内容之外,还有其他方法可以访问它:

When a Python list is known to always contain a single item, is there 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

许多其他方法(结合或改变以上内容,或者依赖于隐式迭代),但是您明白了.

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

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

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