Slices at multiple intervals?
I have a file where I want to extract columns 2, 3, 4, 5 and column -4. These columns are not contiguous.
For clarity reasons, I would like to do something like
values = line.split()[columns_to_extract]
instead
values_part_one = line.split()[columns_to_extract_one]
values_part_two = line.split()[columns_to_extract_two]
So I would like to make a slice that contains positions 2, 3, 4, 5 and -4 so that I can retrieve the values in one line. Is it possible?
If not, are there any other neat oneliners out there that could do this?
source to share
Can a slice be made for this? Not.
However, all is not lost! You can use operator.itemgetter
:
getter = operator.itemgetter(2, 3, 4, 5, -4)
Example:
>>> import operator
>>> getter = operator.itemgetter(2, 3, 4, 5, -4)
>>> getter(range(50)) # Note, returns a `tuple`
(2, 3, 4, 5, 46)
source to share
parts = line.split()
values_part_one = [parts[i] for i in columns_to_extract_one]
values_part_two = [parts[i] for i in columns_to_extract_two]
or as @mgilson points out, you can use operator.itemgetter
to get tuples:
import operator
extract_one = operator.itemgetter(*columns_to_extract_one) # or list explicitly
extract_two = operator.itemgetter(*columns_to_extract_two) # if using fixed cols
parts = line.split()
values_part_one = extract_one(parts)
values_part_Two = extract_two(parts)
Note that both of these will fail IndexError
if the item you are trying to retrieve is not large enough to contain all of the specified indices.
source to share