蟒蛇:如何辨别一个变量是一个数组或一个标 [英] python: how to identify if a variable is an array or a scalar

查看:146
本文介绍了蟒蛇:如何辨别一个变量是一个数组或一个标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,参数 NBins 。我想对这个函数的调用与标 50 或数组 [0,10,20,30] 。我怎样才能识别功能中,是什么 NBins 的长度?或不同地表示,如果它是一个标量或向量?

我试过这样:

 >>> N = [2,3,5]
>>> P = 5
>>> LEN(N)
3
>>> LEN(P)的
回溯(最近通话最后一个):
  文件<&标准输入GT;,1号线,上述<&模块GT;
类型错误:类型'诠释'对象没有LEN()
>>>

正如你所见,我可以不适用 LEN P ,因为它不是一个数组... 。有什么样 IsArray的 isscalar 在Python?

感谢


解决方案

 >>> isinstance([0,10,20,30],清单)
真正
>>> isinstance(50,清单)

要支持任何类型的序列,检查 collections.Sequence 而不是列表

注意 isinstance 还支持类的元组,检查式(X)中(... ...)应避免与是不必要的。

您可能也想检查不isinstance(X,(STR,UNI code))

I have a function that takes the argument NBins. I want to make a call to this function with a scalar 50 or an array [0, 10, 20, 30]. How can I identify within the function, what the length of NBins is? or said differently, if it is a scalar or a vector?

I tried this:

>>> N=[2,3,5]
>>> P = 5
>>> len(N)
3
>>> len(P)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()
>>> 

As you see, I can't apply len to P, since it's not an array.... Is there something like isarray or isscalar in python?

thanks

解决方案

>>> isinstance([0, 10, 20, 30], list)
True
>>> isinstance(50, list)
False

To support any type of sequence, check collections.Sequence instead of list.

note: isinstance also supports a tuple of classes, check type(x) in (..., ...) should be avoided and is unnecessary.

You may also wanna check not isinstance(x, (str, unicode))

这篇关于蟒蛇:如何辨别一个变量是一个数组或一个标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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