简体   繁体   中英

Why does Python operator.itemgetter work given a comma separated list of numbers as indices, but not when the same list is packaged in a variable?

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM