国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

python learn 02 senior more

nanchen2251 / 1207人閱讀

摘要:如果使用的是前綴,多余的參數(shù)則會被認(rèn)為是一個字典的鍵值對。表達(dá)式語句被用來創(chuàng)建新的函數(shù)對象,并且在運行時返回它們。函數(shù)函數(shù)用來取得對象的規(guī)范字符串表示。反引號也稱轉(zhuǎn)換符可以完成相同的功能。基本上,函數(shù)和反引號用來獲取對象的可打印的表示形式。

Content List

1.Datastruct

1.1 List

1.2 Tuple

1.3 Dict

1.4 Seq

2.I/O

2.1 File

2.2 儲存與取儲存

3.Exception

3.1 try...except

3.2 try...finally

4.Python more

4.1 list_comprehension

4.2 function 接收 tuple和list

4.3 lambda 表達(dá)式

4.4 exec和eval語句

4.5 assert 語句

4.6 repr 函數(shù)

1. Datastruct 1.1 List
#!/usr/bin/python
# Filename: using_list.py

# This is my shopping list
shoplist = ["apple", "mango", "carrot", "banana"]

print "I have", len(shoplist)," ."

for item in shoplist:
  print item,

print("
")

shoplist.append("rice")
print "My shopping list is now", shoplist

shoplist.sort()
print "Sorted shopping list is", shoplist

print "The first item I will buy is", shoplist[0]
olditem = shoplist[0]
del shoplist[0]
print "I bought the", olditem
print "My shopping list is now", shoplist

output

? code git:(master) ? ./using_list.py
I have 4 .
apple mango carrot banana

My shopping list is now ["apple", "mango", "carrot", "banana", "rice"]
Sorted shopping list is ["apple", "banana", "carrot", "mango", "rice"]
The first item I will buy is apple
I bought the apple
My shopping list is now ["banana", "carrot", "mango", "rice"]

1.2 Tuple

tuple element polymorphic

#!/usr/bin/python
# Filename: using_tuple.py

zoo = ("wolf", "elephant", "penguin")
print "Number of animals in the zoo is", len(zoo)

new_zoo = ("monkey", "dolphin", zoo)
print "Number of animals in the new zoo is", len(new_zoo)
print "All animals in new zoo are", new_zoo
print "Animals brought from old zoo are", new_zoo[2]
print "Last animal brought from old zoo is", new_zoo[2][2]

output

$ python using_tuple.py
Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are ("monkey", "dolphin", ("wolf", "elephant", "penguin"))
Animals brought from old zoo are ("wolf", "elephant", "penguin")
Last animal brought from old zoo is penguin

using tuple output...

#!/usr/bin/python
# Filename: print_tuple.py

age = 22
name = "Swaroop"

print "%s is %d years old" % (name, age)
print "Why is %s playing with that python?" % name
1.3 Dict
#!/usr/bin/python
# Filename: using_dict.py

# "ab" is short for "a"ddress"b"ook

ab = {       "Swaroop"   : "swaroopch@byteofpython.info",
             "Larry"     : "larry@wall.org",
             "Matsumoto" : "matz@ruby-lang.org",
             "Spammer"   : "spammer@hotmail.com"
     }

print "Swaroop"s address is %s" % ab["Swaroop"]

# Adding a key/value pair
ab["Guido"] = "guido@python.org"

# Deleting a key/value pair
del ab["Spammer"]

print "
There are %d contacts in the address-book
" % len(ab)
for name, address in ab.items():
    print "Contact %s at %s" % (name, address)

if "Guido" in ab: # OR ab.has_key("Guido")
    print "
Guido"s address is %s" % ab["Guido"]
1.4 Seq

List、Tuple、Str 都是 Seq,但是序列是什么,它們?yōu)槭裁慈绱颂貏e呢?序列的兩個主要特點是索引操作符和切片操作符。

#!/usr/bin/python
# Filename: seq.py

# Slicing on a string
name = "swaroop"
print "characters 1 to 3 is", name[1:3]
print "characters 2 to end is", name[2:]
print "characters 1 to -1 is", name[1:-1]
print "characters start to end is", name[:]

// mystr = name[:] # make a copy by doing a full slice, deep copy
2. I/O 2.1 File
#!/usr/bin/python
# Filename: using_file.py

poem = """
Programming is fun
When the work is done
if you wanna make your work also fun:
        use Python!
"""

f = file("poem.txt", "w") # open for "w"riting
f.write(poem) # write text to file
f.close() # close the file

f = file("poem.txt")
# if no mode is specified, "r"ead mode is assumed by default
while True:
    line = f.readline()
    if len(line) == 0: # Zero length indicates EOF
        break
    print line,
    # Notice comma to avoid automatic newline added by Python
f.close() # close the file
2.2 儲存與取儲存

Object to FIle 的 W/R

#!/usr/bin/python
# Filename: pickling.py
## import..as語法。這是一種便利方法,以便于我們可以使用更短的模塊名稱

import cPickle as p
#import pickle as p

shoplistfile = "shoplist.data"
# the name of the file where we will store the object

shoplist = ["apple", "mango", "carrot"]

# Write to the file
f = file(shoplistfile, "w")
p.dump(shoplist, f) # dump the object to a file
f.close()

del shoplist # remove the shoplist

# Read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist

輸出

$ python pickling.py
["apple", "mango", "carrot"]

3. Exception 3.1 try...except
#!/usr/bin/python
# Filename: try_except.py

import sys

try:
    s = raw_input("Enter something --> ")
except EOFError:
    print "
Why did you do an EOF on me?"
    sys.exit() # exit the program
except:
    print "
Some error/exception occurred."
    # here, we are not exiting the program

print "Done"
3.2 try...finally

無論異常發(fā)生與否的情況下都關(guān)閉文件

#!/usr/bin/python
# Filename: finally.py

import time

try:
    f = file("poem.txt")
    while True: # our usual file-reading idiom
        line = f.readline()
        if len(line) == 0:
            break
        time.sleep(2)
        print line,
finally:
    f.close()
    print "Cleaning up...closed the file"
3.3 異常總結(jié)
>>> raise Exception("hello") 引發(fā)異常 raise 異常類/異常實例  
>>> import exceptions  
Exception 是所有異常的基類  

@學(xué)習(xí)摘錄 301:自定義異常類  
 —— class SomeCustomException(Exception) : pass  
 
@學(xué)習(xí)摘錄 302:捕獲異常  
 try :  
     x = input("x : ")  
     y = input("y : ")   
     print x / y  
 except ZeroDivisionError :  
     print "The second num can"t zero!"  
 except TypeError :  
     print "That wasn"t a number."  
@學(xué)習(xí)摘錄 303:用一個塊捕捉兩個異常  
 try :  
     x = input("x : ")  
     y = input("y : ")   
     print x / y  
 except (ZeroDivisionError, TypeError), e :  
     print e  
 except : 這樣子寫的話,就是捕捉所有異常了,不推薦!  
@學(xué)習(xí)摘錄 304:異常上浮-主程序-堆棧跟蹤  
     try  
     except :  
     else :  
     finally : 最后  
4. Python more 4.1 list_comprehension
#!/usr/bin/python
# Filename: list_comprehension.py

listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print listtwo
4.2 function 接收 tuple和list
#!/usr/bin/python
# Filename: powersum.py

def powersum(power, *args):
    """Return the sum of each argument raised to specified power."""
    total = 0
    for i in args:
        total += pow(i, power)
    return total

print powersum(2, 3, 4)
print
print powersum(2, 10)

由于在args變量前有前綴,所有多余的函數(shù)參數(shù)都會作為一個元組存儲在args中。如果使用的是*前綴,多余的參數(shù)則會被認(rèn)為是一個字典的鍵/值對。

4.3 lambda表達(dá)式

lambda 語句被用來創(chuàng)建新的函數(shù)對象,并且在運行時返回它們。

#!/usr/bin/python
# Filename: lambda.py

def make_repeater(n):
    return lambda s: s*n

twice = make_repeater(2)

print twice("word")
print twice(5)

wordword
10

4.4 pass,exec,eval語句

exec語句用來執(zhí)行儲存在字符串或文件中的Python語句。例如,我們可以在運行時生成一個包含Python代碼的字符串,然后使用exec語句執(zhí)行這些語句。下面是一個簡單的例子。

>>> exec "print "Hello World""
Hello World

eval語句用來計算存儲在字符串中的有效Python表達(dá)式。下面是一個簡單的例子。

>>> eval("2*3")
6
4.5 assert語句

assert語句用來聲明某個條件是真的。例如,如果你非常確信某個你使用的列表中至少有一個元素,而你想要檢驗這一點,并且在它非真的時候引發(fā)一個錯誤,那么assert語句是應(yīng)用在這種情形下的理想語句。當(dāng)assert語句失敗的時候,會引發(fā)一個AssertionError。

>>> mylist = ["item"]
>>> assert len(mylist) >= 1
>>> mylist.pop()
"item"
>>> assert len(mylist) >= 1
Traceback (most recent call last):
  File "", line 1, in ?
AssertionError
4.6 repr函數(shù)

repr函數(shù)用來取得對象的規(guī)范字符串表示。反引號(也稱轉(zhuǎn)換符)可以完成相同的功能。注意,在大多數(shù)時候有eval(repr(object)) == object。

>>> i = [] // i = list()
>>> i.append("item")
>>> i
["item"]
>>> `i`
"["item"]"
>>> repr(i)
"["item"]"
>>>

基本上,repr函數(shù)和反引號用來獲取對象的可打印的表示形式。你可以通過定義類的__repr__方法來控制你的對象在被repr函數(shù)調(diào)用的時候返回的內(nèi)容。

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/37909.html

相關(guān)文章

  • 分類算法之決策樹(應(yīng)用篇)

    摘要:起步在理論篇我們介紹了決策樹的構(gòu)建和一些關(guān)于熵的計算方法,這篇文章將根據(jù)一個例子,用代碼上來實現(xiàn)決策樹。轉(zhuǎn)化文件至可視化決策樹的命令得到一個文件,打開可以看到?jīng)Q策樹附錄本次應(yīng)用的全部代碼向量化向量化構(gòu)造決策樹保存模型測試數(shù)據(jù) 起步 在理論篇我們介紹了決策樹的構(gòu)建和一些關(guān)于熵的計算方法,這篇文章將根據(jù)一個例子,用代碼上來實現(xiàn)決策樹。 實驗環(huán)境 操作系統(tǒng): win10 64 編程語言: ...

    luoyibu 評論0 收藏0
  • 【機器學(xué)習(xí)】深度學(xué)習(xí)開發(fā)環(huán)境搭建

    摘要:打開命令提示符輸入出現(xiàn)下面提示說明已經(jīng)安裝成功安裝添加的環(huán)境變量環(huán)境變量中加上的路徑,例如。在命令提示符輸入安裝完成,建立一個全新的環(huán)境,例如我們想建立一個叫的開發(fā)環(huán)境,路徑為,那么我們輸入安裝完成。 工欲善其事,必先利其器。首先我們需要花費一些時間來搭建開發(fā)環(huán)境。 1.安裝python。python是人工智能開發(fā)首選語言。 2.安裝virtualenv。virtualenv可以為一個...

    galaxy_robot 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<