Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

Getting only element from a single-element list in Python?

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Raises exception if not exactly one item:

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

All others silently ignore spec violation, producing first or last item:

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

Rampant insanity:

# But also the only way to retrieve a single item and raise an exception on failure
# for too many, not just too few, elements as an expression, rather than a statement,
# without resorting to defining/importing functions elsewhere to do the work
singleitem = (lambda x: x)(*mylist)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...