简体   繁体   中英

Python: Inconsistency in itemgetter()

I had a strange bug in my code and traced it back to the following behavior of itemgetter :

>>> from operator import itemgetter
>>> l = ['abc', 'def', 'ghi']
>>> index_list_1 = [0]
>>> index_list_2 = [0, 1]
>>> list(itemgetter(*index_list_1)(l))
['a', 'b', 'c']
>>> list(itemgetter(*index_list_2)(l))
['abc', 'def']

The output I wanted with index_list_1 would be ['abc'] , but if itemgetter only has one item to extract, it returns the element instead of a one-tuple.

Am I using itemgetter in the wrong way?

How can I make sure that I get a singleton list if just extracting one value?

Everything looks good: itemgetter(*[0])(['abc']) returns abc and you're building a list from that. list('abc') converts its input to a list and returns ['a', 'b' 'c'] .

One stupid way to solve the problem is:

list(itemgetter(*l+[l[-1]])(m))[:-1]

... or

list(itemgetter(*l)(m)) if len(l) > 1 else [m[l[0]]]

where l is the list of indeces to extract the values for an m is the list of values.

This does not work if l is the empty list but itemgetter cannot deal with this case either although the consistent behavior would be to return () .

The behavior of itemgetter is very unfortunate.

The best option in this case might be to do

[m[i] for i in l]

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