当前位置:首页 » 编程语言 » python的nonzero

python的nonzero

发布时间: 2022-04-24 18:17:47

python提供了三种基本的数字类型

整数、浮点数

㈡ python的错误,关于机器学习实战那本书的kmeans算法

正好我也看到这个问题就实践了一下:

1.矩阵中.A表示返回自身数据的2维数组的一个视图,没有任何拷贝(其实这里的意思没懂,视图?)

2.a[:,0]表示取出矩阵中所有第一列的数据

3.a[:,0].A==1 会得到一个布尔型的数组array([[ True], [False], [False]], dtype=bool)

4.nonzeros(a)返回数组a中值不为0的元素的下标,因此nonzero(a[:,0].A==1)得到的是

一个长度为2的元组(array([0]), array([0])),表示第0行第0列的元素值是不为0的(即为True的)

5.在这里由于只有一列数据,而程序中只要知道是那些行是满足要求的(即那些元素是属于该质心的) ,所以取上面元组的第0个数据就可以了,例如a[nonzero(a[:,0].A==1)[0]]得到的是 matrix([[1, 2, 3]]);

㈢ python2.7.3和3.3.2的区别

转自:http://my.oschina.net/chihz/blog/123437
这边只说明面向对象方面的,其他方面见上面链接

面向对象
(1) 经典类和新式类
Python OO最神奇的地方就是有两种类,经典类和新式类。
新式类跟经典类的差别主要是以下几点:
1. 新式类对象可以直接通过__class__属性获取自身类型:type
2. 继承搜索的顺序发生了改变,经典类多继承属性搜索顺序: 先深入继承树左侧,再返回,开始找右侧;新式类多继承属性搜索顺序: 先水平搜索,然后再向上移动
3. 新式类增加了__slots__内置属性, 可以把实例属性的种类锁定到__slots__规定的范围之中。
4. 新式类增加了__getattribute__方法
Python 2.x中默认都是经典类,只有显式继承了object才是新式类
Python 3.x中默认都是新式类,不必显式的继承object
python 2.x:
>>> ClassicClass.__class__
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
AttributeError: class ClassicClass has no attribute '__class__'
>>> class NewClass(object):
... pass
...
>>> NewClass.__class__

python 3.x:
>>> class NewClass:pass
...
>>> NewClass.__class__
<class 'type'>
(2) 无绑定方法
在Python 2.x中除了类方法和静态方法,其余的方法都必须在第一个参数传递self跟实例绑定,但是在Python 3.x中废除了这条规定,允许方法不绑定实例,这样的方法跟普通的函数没有区别:
Python 2.x:
>>> class MyClass:
... def function():
... print "function"
...
>>> MyClass.function()
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
TypeError: unbound method function() must be called with MyClass instance as first argument (got nothing instead)
>>> m = MyClass()
>>> m.function()
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
TypeError: function() takes no arguments (1 given)
Python 3.x:
>>> class MyClass:
... def function():
... print("function")
...
>>> MyClass.function()
function
>>> m = MyClass()
>>> m.function()
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
TypeError: function() takes no arguments (1 given)
(3) 重要的重载
1. next()和__next__():这应该是继print之后第二大坑爹的不兼容吧,Python程序漫山遍野都是迭代器,但是2和3之间迭代器的实现接口方法名是不同的……嗯,啥都不说了。
2. 分片拦截:Python 3.x之前, 类可以定义__getslice__和__setslice__方法来专门拦截分片,并且这两个方法优先于__getitem__和__setitem__, 但是Python 3.x时代这俩方法再也不存在了,全部的工作都交给了__getitem__和__setitem__,因此在使用这两个方法之前要先判断传递进参数的类型是不是slice对象。
3. __bool__方法:我们知道Python中默认将所有的空对象定义为布尔意义上的False,在自己定义的类中我们也可以加入自定义的布尔判断标准,在2.x中这个方法名叫做__nonzero__, 这个名字显然非常不直观并且不科学!所有考试交白卷的孩子我们都要否定他们的才能么?显然不能!因此Python 3.x中这个方法被重名命为__bool__
4. 3.x 取消了用于大小比较的__cmp__方法,取而代之的是:__lt__、__gt__、__le__、__ge__、__eq__、__ne__,嗯,我感觉这个想法真是不能苟同……有谁能说服我给我洗脑让我爱上这一堆__lt__、__gt__、__le__、__ge__、__eq__、__ne__么。。。
(4) 类修饰器
在我的上一篇博客中秀了一把函数装饰器在表单验证中的使用,http://my.oschina.net/chihz/blog/122897
在3.x的时代,类也有装饰器了,这个装饰器威力巨大,能把装饰的类搞的面目全非,总之想怎么搞就怎么搞,用法同函数装饰器基本一致,只不过传递的参数是类型:
>>> def shutdown(cls):
... def shutdown_func(self):
... print("do something...")
... cls.shutdown = shutdown_func
... return cls
...
>>> @shutdown
... class Test:pass
...
>>> t = Test()
>>> t.shutdown()
do something...

异常

先来看一段代码
python 2.x:
>>> class Person:
... def __init__(self, msg):
... self.msg = msg
...
>>> try:
... raise Person, "woca"
... except Person as p:
... print p.msg
...
woca
python 3.x:
>>> class Person:
... def __init__(self, msg):
... self.msg = msg
...
>>> try:
... raise Person("woca")
... except Person as p:
... print(p.msg)
Traceback (most recent call last):
File "<stdin>", line 2, in <mole>
TypeError: exceptions must derive from BaseException

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 3, in <mole>
TypeError: catching classes that do not inherit from BaseException is not allowed
>>>
接下来说不同:
1. 在2.x时代,所有类型的对象都是可以被直接抛出的,在3.x时代,只有继承自BaseException的对象才可以被抛出。
2. 2.x raise语句使用逗号将抛出对象类型和参数分开,3.x取消了这种奇葩的写法,直接调用构造函数抛出对象即可。
在2.x时代,异常在代码中除了表示程序错误,还经常做一些普通控制结构应该做的事情,在3.x中可以看出,设计者让异常变的更加专一,只有在错误发生的情况才能去用异常捕获语句来处理。

㈣ python 中if判断下面为空会怎么样

不进行循环。
ifa会首先去调用a的__nonzero__()去判断a是否为空,并返回True/False,若一个对象没有定义__nonzero__(),就去调用它的__len__()来。
Python中的if条件控制语句,让程序做出准确判断Python中常用的条件控制语句是if语句。

㈤ 您好,有关于Python的问题,想要请教你,方便加您的可以直接沟通的方式吗

可以呀
Common Stumbling Blocks
本段简单的列出容易使人出错的变动(初学者应该注意)。
· print语句被print()函数取代了,可以使用关键字参数来替代老的print特殊语法。例如:
Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x, # 使用逗号结尾禁止换行
New: print(x, end=" ") # 使用空格代替换行

Old: print # 输出新行
New: print() # 输出新行

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y) # 输出repr((x, y))
New: print((x, y)) # 不同于print(x,y)!

你可以自定义输出项之间的分隔符:
print("There are <", 2**32, ">possibilities!", sep="")
输出结果是:
There are <4294967296> possibilities!

注意:

print()函数不支持老print语句的"软空格"特性,例如,在python2.x中,print "A\n", "B"会输出"A\nB\n",而python3.0中,print("A\n","B")会输出"A\n B\n"

使用 2to3 源码转换工具时,所有的print语句被自动转换成print()函数调用,对大项目,这是无需争论的。
· python3.0使用字符串(strings)和bytes代替Unicode字符串和8位字符串,这意味着几乎所有使用Unicode编码和二进制数据的代码都要改动。这个改动很不错,在2.x的世界里,无数的bug都是因为编码问题。
· map()和filter()返回迭代器(iterators)
· dict方法keys(),items(),values()返回视图(同样是迭代器)而不是列表(list)
· 内建的sorted()方法和list.sort()方法不再接受表示比较函数的cmp参数,使用key参数代替。
· 1/2返回浮点数,使用1//2能得到整数。
· repr()函数对于long整数不再包含拖尾的L,所以不加判断的去除最后一个字符会导致去掉一个有用的数字。
String and Bytes
· 现在只有一种字符串:str,它的行为和实现都很像2.x的unicode串。
· basestring超类已经去掉了,2to3 工具会把每个出现的basestring替换成str。
· PEP3137:新类型bytes,用来表示二进制数据和编码文本,str和bytes不能混合,需要时,必须进行显示的转换,转换方法是str.encode()(str->bytes)和bytes.decode()(bytes->str).
· 在原始字符串(raw strings)中所有反斜线都按字面量解释,不再特殊处理Unicode转义字符。
· PEP3112:bytes字面量,例如b"abc",创建bytes实例。
· PEP3120:默认源文件编码为UTF-8
· PEP3131:可以使用非ASCII标识符(然而,除了注释中贡献者的名字之外,标准库仍然只包含ASCII)
· PEP3116:新的IO实现,API几乎100%向后兼容,二进制文件使用bytes代替strings
· 去除了StringIO和cStringIO模块,取而代之的是io.StringIO或者io.BytesIO
PEP3101:字符串格式化的新方法
· str.format方法(原文提到替代了%操作符,实际上,format方法和%的用法差别很大,各有所长)。
PEP3106:修补了dict的keys(),items(),values()方法
· 删除了dict.iterkeys(),dict.itervalues()和dict.iteritems()
· dict.keys(),dict.values()和dict.items()返回dict相关数据的引用
PEP3107:函数注解(FunctionAnnotations)
· 注解函数参数和返回值的标准化方法
Exception Stuff
· PEP352:异常类必须继承自BaseException,它异常结构的基类。
· 移除了StandardError
· Dropping sequence behavior (slicing!)and message attribute of exception instances.
· PEP3109:抛出异常:现在必须使用raiseException(args)而不是原来的raise Exception, args
· PEP3110:捕获异常,现在必须使用exceptException as identifier而不是原来的except Exception,identifier
· PEP3134:异常链(Exceptionchain)。
· 改良了一些windows不能加载模式时的异常信息,具有本地化处理。
New Class and Metaclass Stuff
· 移除了classic class
· PEP3115:新的metaclass语法
· PEP3119:抽象基类。
· PEP3129:类包装。
· PEP3141:数字抽象基类
其他的语言变化

这里列出大多数的Python语言核心和内建函数的变化。
· 移除了backticks(使用repr()代替)
· 移除了<>(不等号,使用!=代替)
· as和with变成了关键字
· True,False和None变成了关键字
· PEP237:long不存在了,只有int,它和原来的long一样。不再支持以L结尾的数字字面量。移除sys.maxint,因为int现在已经是无限大了
· PEP238:int相除,返回float
· 改变了顺序操作符的行为,例如x<y,当x和y类型不匹配时抛出TypeError而不是返回随即的bool值
· 移除了__getslice__,语法a[i:j]被解释成a.__getitem__(slice(i,j))
· PEP3102:keyword-only arguments.在函数参数列表中,出现在*args之后的命名参数只能使用"关键字参数"的形式调用
· PEP3104:nonlocal声明。使用nonlocal可以声明一个外部变量(不是global变量)
· PEP3111:raw_input() 改名为input(),也就是说,新的input()函数从标准输入设备(sys.stdin)读取一行并返回(不包括行结束符),如果输入过早终止,该函数抛出EOFError,如果想使用老的input(),可以使用(input())代替。
· xrange()改名为range(),range()现在不是产生一个列表(list),而是一个迭代器。
· PEP3113:移除了"元组参数拆包(tuple parameter unpacking)"。这种写法已经不行了:
1. deffoo(a, (b, c)):…
2.
3. 现在要这样写:
4.
5. deffoo(a, b_c):
6. b,c = b_c
· PEP3114:next()重命名为__next__(),新的内建函数next()可以调用一个对象的__next__()方法。
· PEP3127:新的八进制字面量,二进制字面量和bin()函数。你应该写0o666而不是0666,oct()函数也做了响应的改动。同样,0b1010等价于10,bin(10)返回"0b1010″。0666这种写法现在是错误的。
· PEP3132:支持迭代器拆包。现在你可以这样写:
1 a,b, *rest = some_seqence
2
3 甚至象这样:
4
5 *rest,a = stuff
6 一般情况下,rest对象是list,而等号右边的对象是可迭代的
· PEP3135:新的super()。你可以不适用任何参数调用super(),正确的参数和实例会被正确选择。如果使用参数,它的行为不变,和以前一样。
· zip(),map(),filter()返回迭代器。
· 移除了string.letters和它的小伙伴们(string.lowcase和string.uppercase),现在上场的是string.ascii_letters等
· 移除了apply(),callable(),exefile(),file(),rece(),reload()
· 移除了dict.has_key()。使用in操作符进行测试
· exec语句没有了,现在是exec()函数
· 移除了__oct__()和__hex__()特殊方法。oct()和hex()方法使用__index__()
· 移除了对__members__和__methods__的支持
· nb_nonzero重命名为nb_bool,__nonzero__()重命名为__bool__()
Optimizations
· 一般情况下,python 3.0比python 2.5慢33%左右。不过仍有提升空间。
模块变动(新的,改进的和废弃的)
· 移除了cPickle模块,可以使用pickle模块代替。最终我们将会有一个透明高效的模块。
· 移除了imageop模块
· 移除了audiodev, Bastion, bsddb185,exceptions, linuxaudiodev, md5, MimeWriter, mimify, popen2, rexec, sets, sha,stringold, strop, sunaudiodev, timing和xmllib模块
· 移除了bsddb模块(单独发布,可以从获取)
· 移除了new模块
· os.tmpnam()和os.tmpfile()函数被移动到tmpfile模块下
· tokenize模块现在使用bytes工作。主要的入口点不再是generate_tokens,而是tokenize.tokenize()
Build and C API Changes

Python's build process和C API的改动包括:
· PEP3118:新的Buffer API
PEP3121:扩展模块的的Initialization& Finalization
· PEP3123:使PyObject_HEAD符合标准C
其他的改动和修复

㈥ python的特殊方法__nonzero__()怎么用什么情况就会调用它,举个例子,谢谢

类的__nonzero__方法用于将类转换为布尔值。通常在用类进行判断和将类转换成布尔值时调用。比如语句if A: print 'foo'中就会调用A.__nonzero__()来判断。下面这个程序应该能帮助你理解__nonzero__的作用。

class A:
def __nonzero__(self):
print 'A._nonzero__()'
return True

print 'A is not zero' if A() else 'A is zero'
print bool(A())

㈦ Python内部是如何判断一个对象是True还是False

作者:gao xinge
链接:https://www.hu.com/question/53708403/answer/139331035
来源:知乎
着作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

内建函数boolpython中的所有对象都可以用内建函数bool来判断布尔值是True还是False,如下>>> bool(1)
True
>>> bool(0)
False
>>> bool(True)
True
>>> bool(False)
False
>>> def f(a):
return a
>>> bool(f)
True
>>> bool(__builtins__)
True
>>> import collections
>>> bool(collections)
True
__nonzero__函数和__len__函数内建函数bool的逻辑顺序: 如果对象没有实现__nonzero__函数或者__len__函数,返回True; 如果对象实现了__nonzero__函数,根据__nonzero__函数的返回值判断; 如果对象没有实现__nonzero__函数,但实现了__len__函数,根据__len__函数的返回值判断如下>>> # example one
>>> class f:
def __init__(self, a, b):
self.a = a
self.b = b

>>> t = f(0,1)
>>> bool(t)
True

>>> # example two
>>> class f:
def __init__(self, a, b):
self.a = a
self.b = b
def __nonzero__(self):
return self.a
def __len__(self):
return self.b

>>> t = f(0,1)
>>> bool(t)
False

>>> # example three
>>> class f:
def __init__(self, a, b):
self.a = a
self.b = b
def __len__(self):
return self.b

>>> t = f(1,0)
>>> bool(t)
False

㈧ 如何在Python中获取完整的异颜桓

我们可以很容易的通过Python解释器获取帮助。如果想知道一个对象(object)更多的信息,那么可以调用help(object)!另外还有一些有用的方法,dir(object)会显示该对象的大部分相关属性名,还有object._doc_会显示其相对应的文档字符串。下面对其进行逐一介绍。

1、 help()

help函数是Python的一个内置函数。
函数原型:help([object])。
可以帮助我们了解该对象的更多信息。
Ifno argument is given, the interactive help system starts on the interpreter console.

>>> help()

Welcome to Python 2.7! This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at .

Enter the name of any mole, keyword, or topic to get help on writing
Python programs and using Python moles. To quit this help utility andreturn to the interpreter, just type "quit".

To get a list of available moles, keywords, or topics, type "moles","keywords", or "topics". Each mole also comes with a one-line summary
of what it does; to list the moles whose summaries contain a given word
such as "spam", type "moles spam".

help> int # 由于篇幅问题,此处只显示部分内容,下同Help on class int in mole __builtin__:class int(object)
| int(x=0) -> int or long
| int(x, base=10) -> int or long
|

.....help>

Ifthe argument is a string, then the string is looked up as the name of amole,function,class,method,keyword, ordocumentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

>>> help(abs) # 查看abs函数Help on built-in function abs in mole __builtin__:

abs(...)
abs(number) -> number

Return the absolute value of the argument.>>> help(math) # 查看math模块,此处只显示部分内容Help on built-in mole math:

NAME
math

FILE
(built-in)

DESCRIPTION
This mole is always available. It provides access to the
mathematical functions defined by the C standard.

FUNCTIONS
acos(...)
acos(x)

Return the arc cosine (measured in radians) of x.

.....>>> 293031

2、dir()

dir函数是Python的一个内置函数。
函数原型:dir([object])
可以帮助我们获取该对象的大部分相关属性。
Without arguments, return the list of names in the current local scope.

>>> dir() # 没有参数['__builtins__', '__doc__', '__name__', '__package__']>>> >>> import math # 引入一个包和一个变量,再次dir()>>> a=3>>> >>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'a', 'math']>>> 12345678910

With an argument, attempt to return a list of valid attributes for that object.

>>> import math>>> dir(math) # math模块作为参数['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'sign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']>>> 12345

The default dir() mechanism behaves differently with different types of objects, as it attempts to proce the most relevant, rather than complete, information:
• If the object is a mole object, the list contains the names of the mole’s attributes.

>>> import math>>> dir(math) # math模块作为参数['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'sign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']>>> 12345

• If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.

>>> dir(float) # 类型['__abs__', '__add__', '__class__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__int__', '__le__', '__long__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pos__', '__pow__', '__radd__', '__rdiv__', '__rdivmod__', '__rece__', '__rece_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__setformat__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']>>> dir(3.4)
['__abs__', '__add__', '__class__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__int__', '__le__', '__long__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pos__', '__pow__', '__radd__', '__rdiv__', '__rdivmod__', '__rece__', '__rece_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__setformat__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']>>> >>> class A:
x=3
y=4>>> class B(A):
z=5>>> dir(B) # 类['__doc__', '__mole__', 'x', 'y', 'z']>>> 123456789101112131415161718

• Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

3、_doc_

在Python中有一个奇妙的特性,文档字符串,又称为DocStrings。
用它可以为我们的模块、类、函数等添加说明性的文字,使程序易读易懂,更重要的是可以通过Python自带的标准方法将这些描述性文字信息输出。
上面提到的自带的标准方法就是_doc_。前后各两个下划线。
注:当不是函数、方法、模块等调用doc时,而是具体对象调用时,会显示此对象从属的类型的构造函数的文档字符串。

>>> import math>>> math.__doc__ # 模块'This mole is always available. It provides access to the mathematical functions defined by the C standard.'>>> abs.__doc__ # 内置函数'abs(number) -> number Return the absolute value of the argument.'>>> def addxy(x,y):
'''the sum of x and y'''
return x+y>>> addxy.__doc__ # 自定义函数'the sum of x and y'>>> a=[1,2,4]>>> a.count.__doc__ # 方法'L.count(value) -> integer -- return number of occurrences of value'>>> b=3>>> b.__doc__ # 具体的对象"int(x=0) -> int or long int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) 4">>> 12345678910111213141516171819

其实我们可以通过一定的手段来查看这些文档字符串,比如使用Pycharm,在对应的模块、函数、方法等上鼠标“右击”->Go to->Declaration。例如:查看内置函数abs的文档字符串

参考文献:
1、Python帮助文档

㈨ python nonzero是什么意思

当下标对象是元组,并且其中有布尔数组时,相当于将布尔数组展开为由nonzeros()转换之后的各个整数数组:
>>> a[1:3, b2]
array([[20, 22, 25],
[40, 42, 45]])
>>> a[1:3, np.nonzero(b2)[0], np.nonzero(b2)[1]]
array([[20, 22, 25],
[40, 42, 45]])

㈩ python中数据类型

数字类型:

①整型:

通常被称为是整型或整数,可以是正整数或负整数,不带小数点。Python3整型是没有限制大小的,可以当做long类型使用, 但实际上由于机器内存的有限,我们使用的整数是不可能无限大的。

整型的四种表现形式:

2 进 制:以'0b'开头。例如:'0b11011'表示10进制的27
8 进 制:以'0o'开头。例如:'0o33'表示10进制的27
10进制:正常显示
16进制:以'0x'开头。例如:'0x1b'表示10进制的27
各进间数字进行转换(内置函数):

bin(i):将i转换为2进制,以“0b”开头。

oct(i):将i转换为8进制,以“0o”开头。

int(i):将i转换为10进制,正常显示。

hex(i):将i转换为16进制,以“0x”开头。



②浮点数:

浮点型由整数部分与小数部分组成,浮点型也可以使用科学计数法表示(2.5e2 = 2.5 x 102 = 250)

③布尔类型:

所有标准对象均可用于布尔测试,同类型的对象之间可以比较大小。每个对象天生具有布尔True或False值。空对象,值为零的任何数字或者Null对象None的布尔值都是False。在Python3中True=1,False=0,可以和数字型进行运算。

下列对象的布尔值是False:

None;False;0(整型),0.0(浮点型);0L(长整形);0.0+0.0j(复数);“”(空字符串);[](空列表);()(空元组);{}(空字典)。

值不是上列的任何值的对象的布尔值都是True,例如non-empty,non-zero等。用户创建的类实例如果是定义了nonzero(_nonzeor_())或length(_len_())且值为0,那么它们的布尔值就是False。

④复数:

复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型。





热点内容
phprecv 发布:2025-05-17 11:55:00 浏览:610
福建时钟监控网关服务器云主机 发布:2025-05-17 11:54:28 浏览:248
c数据库压缩 发布:2025-05-17 11:39:22 浏览:960
安卓手机如何连接音响功放 发布:2025-05-17 11:37:48 浏览:958
破解exe加密视频 发布:2025-05-17 11:23:41 浏览:976
我的世界服务器圈太大了怎么办 发布:2025-05-17 11:15:21 浏览:614
便宜的免费云服务器 发布:2025-05-17 11:08:50 浏览:779
中国顶级dhcp解析服务器地址 发布:2025-05-17 11:06:27 浏览:36
php转义html 发布:2025-05-17 11:04:00 浏览:569
钢筋笼加密区规范 发布:2025-05-17 10:59:50 浏览:6