python - 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
以错误的方式使用?
如果仅提取一个值,如何确保获得单例列表?
解决方案
一切看起来都不错:itemgetter(*[0])(['abc'])
返回abc
并且您正在list
从中构建一个。list('abc')
将其输入转换为 alist
并返回['a', 'b' 'c']
。
推荐阅读
- visual-studio-2010 - SSRS 报告无法通过计划订阅工作,但可以正常工作
- raspberry-pi - OSError:/lib/aarch64-linux-gnu/libgomp.so.1:无法在静态 TLS 块中分配内存
- ios - 无法在提醒.0 中存储 __SwiftValue 类型的对象
- php - 编辑列日期格式后不显示过滤日期 - Laravel Yajra Datatable
- python - CSV行跳转功能
- javascript - 在'.'中访问javascript中对象的数字元素的方式 导致错误
- windows - 某些元素在检查工具中显示时未被 Flaui 识别,并且未像在应用程序中那样读取 value 属性
- javascript - 如何访问组件内的全局变量?
- html - Ionic5/Angular - 尝试区分“[object Object]”时出错。只允许使用数组和可迭代对象
- amazon-web-services - AWS OpenSearch OpenIdConnect 作为身份验证方法