Here is a demonstration of the issue I'm having. I'm fairly new to Python, so I'm pretty sure I'm overlooking something very obvious.
import operator
lista=["a","b","c","d","e","f"]
print operator.itemgetter(1,3,5)(lista)
>> ('b', 'd', 'f')
columns=1,3,5
print operator.itemgetter(columns)(lista)
>> TypeError: list indices must be integers, not tuple
How do I get around this issue so I can use an arbitrary list of indices specified as an argument at program start?
itemgetter() for the key parameter. itemgetter() in the standard library operator returns a callable object that fetches a list element or dictionary value. You sort a two-dimensional list according to the value of any position (index) with operator.
itemgetter(n) constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it. So, here's an important note: in python functions are first-class citizens, so you can pass them to other functions as a parameter.
attrgetter (attr) operator. attrgetter (*attrs) Return a callable object that fetches attr from its operand. If more than one attribute is requested, returns a tuple of attributes.
This isn't about itemgetter, but about function calling syntax. These are different things:
operator.itemgetter(1, 3, 5)
operator.itemgetter((1, 3, 5))
The first one gets you item #1, item #3, and item #5. The second one gets you item #(1, 3, 5). (Which may make sense for a dictionary, but not for a list.)
The second one is what you get when you use itemgetter(columns)
. So, how do you get the first?
operator.itemgetter(*columns)
That's it.
See Unpacking Argument Lists in the tutorial for more information.
You need to pass individual arguments to itemgetter
. columns
here is a tuple (1, 3, 5)
You can use the *
operator to unpack it in the function call. The *
expands a list or tuple so that its values are sent as individual arguments, rather than passing the entire tuple as one argument.
For example: func(*(1, 2, 3))
== func(1, 2, 3)
so what you need is:
columns=1,3,5
print operator.itemgetter(*columns)(lista)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With