仅从 Python 中的单元素列表中获取元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33161448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting only element from a single-element list in Python?
提问by Pyderman
When a Python list is known to always contain a single item, is there way to access it other than:
当已知 Python 列表始终包含单个项目时,是否有其他方法可以访问它:
mylist[0]
You may ask, 'Why would you want to?'. Curiosity alone. There seems to be an alternative way to do everythingin Python.
你可能会问,“你为什么要这样做?”。只有好奇心。似乎有一种替代方法可以在 Python 中完成所有工作。
采纳答案by ShadowRanger
Sequence unpacking:
顺序拆包:
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
Explicit use of iterator protocol:
显式使用迭代器协议:
singleitem = next(iter(mylist))
Destructive pop:
破坏性流行:
singleitem = mylist.pop()
Negative index:
负指数:
singleitem = mylist[-1]
Set via single iteration for
(because the loop variable remains available with its last value when a loop terminates):
通过单次迭代设置for
(因为当循环终止时,循环变量仍然可用其最后一个值):
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.
许多其他(组合或改变上述内容,或以其他方式依赖隐式迭代),但您明白了。
回答by pylang
I will add that the more_itertools
library has a tool that returns one item from an iterable.
我将补充一点,该more_itertools
库有一个工具可以从可迭代对象中返回一个项目。
from more_itertools import one
iterable = ["foo"]
one(iterable)
# "foo"
In addition, more_itertools.one
raises an error if the iterable is empty or has more than one item.
此外,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)