How do I select some elements of an x-tuple returned by a function?
I'm new to Python. Consider a function str.partition()
that returns a 3-tuple. If I'm only interested in elements 0 and 2 of this tuple, then what's the best way to select only some of the elements from such a set?
Currently I can do:
# Introduces "part1" variable, which is useless
(part0, part1, part2) = str.partition(' ')
Or:
# Multiple calls and statements, again redundancy
part0 = str.partition(' ')[0]
part2 = str.partition(' ')[2]
I would like to do something like this, but cannot:
(part0, , part2) = str.partition(' ')
# Or:
(part0, part2) = str.partition(' ')[0, 2]
source to share
The underscore is often used as a name for the material you want, so something like this will work:
part0, _, part2 = str.partition(' ')
In this particular case, you can do it, but this is not a very acceptable solution:
part0, part2 = str.partition(' ')[::2]
A more esoteric solution:
from operator import itemgetter
part0, part2 = itemgetter(0, 2)(str.partition(' '))
source to share
That's right, you cannot take multiple special elements from a list of tuples at one time.
part0, part1, part2 = str.partition(' ')
This is the way. Don't worry about part1, if you don't need it, you don't need it. It is common to call it "dummy" or "unused" to indicate that it is not being used.
You can be ugly:
part0, part2 = str.partition(' ')[::2]
In this particular case, but it is confusing and disliked by others.;)
source to share
I think the question I asked a while ago might help you:
Pythonic way to get some rows of a matrix
NumPy gives you the slice syntax that you want to extract from different elements using a tuple or a list of indices, but I don't think you want to convert a list of strings to numpy.array to extract multiple elements, so perhaps you could write assistant:
def extract(lst, *indices):
return [lst[i] for i in indices]
item0, item2 = extract(str.partition(' '), 0, 2)
source to share