从Python中的单元素列表中仅获取元素?

时间:2015-10-16 02:09:27

标签: python python-3.x python-2.7 list iterable-unpacking

当已知Python列表始终包含单个项目时,除了以下方式之外,是否可以访问它:

mylist[0]

你可能会问,'你为什么要这样?'。仅好奇心。似乎有另一种方法可以在Python中执行所有

2 个答案:

答案 0 :(得分:75)

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.

答案 1 :(得分:9)

我将添加more_itertools  library有一个工具可以从一个iterable中返回一个项目。

from more_itertools import one


iterable = ["foo"]
one(iterable)
# "foo"

此外,如果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)