Getting only element from a single-element list in

2019-01-07 18:56发布

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

mylist[0]

You may ask, 'Why would you want to?'. Curiosity alone. There seems to be an alternative way to do everything in Python.

2条回答
我只想做你的唯一
2楼-- · 2019-01-07 19:33

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.

查看更多
叛逆
3楼-- · 2019-01-07 19:41

I will add that the more_itertools library has a tool that returns one item from an 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 = []
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)
查看更多
登录 后发表回答