當前位置:首頁 » 編程語言 » 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都是浮點型。





熱點內容
破解exe加密視頻 發布:2025-05-17 11:23:41 瀏覽:976
我的世界伺服器圈太大了怎麼辦 發布:2025-05-17 11:15:21 瀏覽:614
便宜的免費雲伺服器 發布:2025-05-17 11:08:50 瀏覽:777
中國頂級dhcp解析伺服器地址 發布:2025-05-17 11:06:27 瀏覽:34
php轉義html 發布:2025-05-17 11:04:00 瀏覽:567
鋼筋籠加密區規范 發布:2025-05-17 10:59:50 瀏覽:4
我的世界網易手機版主播伺服器房號 發布:2025-05-17 10:40:59 瀏覽:227
豎編譯 發布:2025-05-17 09:56:08 瀏覽:229
編程畫飛機 發布:2025-05-17 09:54:03 瀏覽:803
手機如何解鎖密碼屏幕鎖怎麼刪除 發布:2025-05-17 09:52:04 瀏覽:125