pythonic way to convert variable to list(pythonic将变量转换为列表的方法)
问题描述
我有一个函数,它的输入参数可以是一个元素或元素列表.如果这个参数是单个元素,那么我将它放在一个列表中,这样我就可以以一致的方式迭代输入.
I have a function whose input argument can either be an element or a list of elements. If this argument is a single element then I put it in a list so I can iterate over the input in a consistent manner.
目前我有这个:
def my_func(input):
if not isinstance(input, list): input = [input]
for e in input:
...
我正在使用现有 API,因此无法更改输入参数.使用 isinstance() 感觉很麻烦,那么有没有正确的方法来做到这一点?
I am working with an existing API so I can't change the input parameters. Using isinstance() feels hacky, so is there a proper way to do this?
推荐答案
我喜欢 Andrei Vajna 对 hasattr(var,'__iter__') 的建议
.请注意一些典型 Python 类型的这些结果:
I like Andrei Vajna's suggestion of hasattr(var,'__iter__')
. Note these results from some typical Python types:
>>> hasattr("abc","__iter__")
False
>>> hasattr((0,),"__iter__")
True
>>> hasattr({},"__iter__")
True
>>> hasattr(set(),"__iter__")
True
这具有将字符串视为不可迭代的额外优势 - 字符串是一个灰色区域,因为有时您希望将它们视为一个元素,而其他时候则视为一个字符序列.
This has the added advantage of treating a string as a non-iterable - strings are a grey area, as sometimes you want to treat them as an element, other times as a sequence of characters.
请注意,在 Python 3 中,str
类型 确实 具有 __iter__
属性,这不起作用:
Note that in Python 3 the str
type does have the __iter__
attribute and this does not work:
>>> hasattr("abc", "__iter__")
True
这篇关于pythonic将变量转换为列表的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:pythonic将变量转换为列表的方法


基础教程推荐
- 对多索引数据帧的列进行排序 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01