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]

      

+2


source to share


5 answers


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(' '))

      

+13


source


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.;)

+4


source


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)

      

+2


source


you can also use str.split(' ', 1)

instead ofstr.partition(' ')

you will return a list instead of a tuple, but you will not return a delimiter

+1


source


This is how I would do it:

all_parts = str.partition(' ')
part0, part2 = all_parts[0], all_parts[2]

      

0


source







All Articles