首页 > 解决方案 > Python:itemgetter()中的不一致

问题描述

我的代码中有一个奇怪的错误,并将其追溯到以下行为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']

我想要的输出index_list_1['abc'],但如果itemgetter只有一项要提取,它会返回元素而不是单元组。

我是否itemgetter以错误的方式使用?

如果仅提取一个值,如何确保获得单例列表?

标签: pythonlistitems

解决方案


一切看起来都不错:itemgetter(*[0])(['abc'])返回abc并且您正在list从中构建一个。list('abc')将其输入转换为 alist并返回['a', 'b' 'c']


推荐阅读