将变量转换为列表的pythonic方法 [英] pythonic way to convert variable to list

查看:93
本文介绍了将变量转换为列表的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方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆