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 everything in Python.
你可能会问,'你为什么要这样?'。仅好奇心。似乎有另一种方法可以在Python中完成所有工作。
2 个解决方案
#1
56
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 singleitem in mylist: break
Many others (combining or varying bits of the above, or otherwise relying on implicit iteration), but you get the idea.
许多其他人(结合或改变上述内容,或以其他方式依赖隐式迭代),但你明白了。
#2
7
I will add that the more_itertools
library has a tool that returns one item from an iterable.
我将补充说,more_itertools库有一个工具可以从一个iterable中返回一个项目。
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.
此外,如果iterable为空或具有多个项目,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)
#1
56
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 singleitem in mylist: break
Many others (combining or varying bits of the above, or otherwise relying on implicit iteration), but you get the idea.
许多其他人(结合或改变上述内容,或以其他方式依赖隐式迭代),但你明白了。
#2
7
I will add that the more_itertools
library has a tool that returns one item from an iterable.
我将补充说,more_itertools库有一个工具可以从一个iterable中返回一个项目。
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.
此外,如果iterable为空或具有多个项目,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)