如何判断python变量是字符串还是列表? [英] How can I tell if a python variable is a string or a list?

查看:710
本文介绍了如何判断python变量是字符串还是列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个例程,该例程将字符串列表作为参数,但是我想支持传递单个字符串并将其转换为一个字符串列表.例如:

I have a routine that takes a list of strings as a parameter, but I'd like to support passing in a single string and converting it to a list of one string. For example:

def func( files ):
    for f in files:
        doSomethingWithFile( f )

func( ['file1','file2','file3'] )

func( 'file1' ) # should be treated like ['file1']

我的函数如何判断是否传递了字符串或列表?我知道有一个type函数,但是有一种更pythonic"的方式吗?

How can my function tell whether a string or a list has been passed in? I know there is a type function, but is there a "more pythonic" way?

推荐答案

好吧,关于类型检查并没有什么异常之处.话虽如此,如果您愿意给来电者带来一点负担:

Well, there's nothing unpythonic about checking type. Having said that, if you're willing to put a small burden on the caller:

def func( *files ):
    for f in files:
         doSomethingWithFile( f )

func( *['file1','file2','file3'] ) #Is treated like func('file1','file2','file3')
func( 'file1' )

我认为这更具有蟒蛇性,因为显式优于隐式".当输入已经是列表形式时,呼叫者至少在此方面可以识别.

I'd argue this is more pythonic in that "explicit is better than implicit". Here there is at least a recognition on the part of the caller when the input is already in list form.

这篇关于如何判断python变量是字符串还是列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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