1. 程式人生 > >python基礎彙總(六)

python基礎彙總(六)

這是最後一篇python基礎彙總了。

在進入正題之前,忍不住嘮叨一句:

python的前途越來越光明,隨著馬雲的無人酒店,無人海底撈陸續面世,python重要性越來越大。

未來是屬於人工智慧的,完成人工智慧的程式碼是python自動化程式碼。

 

我們先來複習一下列表和字典的一些基礎知識。

一.列表

ten_things="Apples Oranges Crows Telephones Light Sugar"

print("Wait there's not 10 things in that list,let's fix that.")

stuff=ten_things.split(' ') #spilt函式的作用,我已經在前面解釋過了,猜猜是啥?

more_stuff=["Day","Night","Song","Frisbee","Corn","Banana","Girl","Boy"]

while len(stuff) !=10:
next_one =more_stuff.pop()
print("Adding: ",next_one)
stuff.append(next_one)
print("There's %d items now."%len(stuff))

print("There we go: ",stuff)

print("Let's do some things with stuff.")

print(stuff[1])

print(stuff[-1])
print(stuff.pop())
print(' '.join(stuff))
print('#'.join(stuff[3:5]))
輸出結果:

Wait there's not 10 things in that list,let's fix that.
Adding: Boy
There's 7 items now.
Adding: Girl
There's 8 items now.
Adding: Banana
There's 9 items now.
Adding: Corn
There's 10 items now.
There we go: ['Apples', 'Oranges', 'Crows', 'Telephones', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']
Let's do some things with stuff.
Oranges
Corn
Corn
Apples Oranges Crows Telephones Light Sugar Boy Girl Banana
Telephones#Light



'''
最後兩句的作用需要弄清楚。
' '.join(stuff)的作用可以理解為join(' '.things),也就是說:
在join函式中,用空格將stuff列表的所有元素取出來並分隔開來。
如果是'%'.join(stuff),輸出結果則是:
Apples%Oranges%Crows%Telephones%Light%Sugar%Boy%Girl%Banana
為什麼沒有corn,是因為在之前已經pop彈出去了
'''

還記得split()函式嗎?-split函式是拆分字串函式的操作,拆分成列表的形式。其中split()括號內的內容不可以為空,必須輸入拆分點。
比如,"i love you yan pao pao",這個字串:如果要拆分這個句子,是不是以空格為拆分點,將單詞全部拆分開來?所以處理這句話,應該是split('  '),將拆分點用引號表示出來。 輸出自然是['i','love','you','yan','pao','pao']。

那麼,如果要拆分"www.baiidu.com"這個字串?這時候拆分點是不是一個英文句號?所以應該這麼處理,split(" . ") 

輸出結果自然是["www","baidu","com"]

 

這段程式碼我們可以學到兩個重要的知識點:

①split(' ')函式,分割字串的操作,目前是使用空格分割。

②' '.join(list)函式,括號內是以list形式存在的變數。

 

二.字典

#create a mapping of state to abbreviation
states={
'Oregon':'OR',
'Florida':'FL',
'California':'CA',
'New York':'NY',
'Michigan':'MI'
}

#create a basic set of states and some cities in them
cities={
'CA':'San Francisco',
'MI':'Detroit',
'FL':'Jacksonville'
}

#add some more cities
cities['NY']='New York'
cities['OR']='Portland'

#print out some cities
print('-'*10)
print("NY state has: ",cities['NY'])
print("OR state has: ",cities['OR'])

#print some states
print('-'*10)
print("Michigan's abbreviation is: ",states['Michigan'])
print("Florida's abbreviation is: ",states['Florida'])

#do it by using the state then cities dict
print('-'*10)
print("Michigan has: ",cities[states['Michigan']])
print("Florida has: ",cities[states['Florida']])

#print every state abbreviation
print('-'*10)
for state,abbrev in states.items():
print("%s is abbreviated %s."%(state,abbrev))

#print every city in state
print('-'*10)
for abbrev,city in cities.items():
print("%s has the city %s."%(abbrev,city))

#now do both at the same time
print('-'*10)
for state,abbrev in states.items():
print("%s state is abbreviated %s and has city %s"%(state,abbrev,cities[abbrev]))

print('-'*10)
#safely get a abbreviation by state that might not be there
state=states.get('Texas',None)

if not state:
print("Sorry,no Texas.")

#get a city with a default value
city=cities.get('Tx','Does Not Exist')
print("The city for the state 'TX' is:%s" %city)
輸出結果:

----------
NY state has: New York
OR state has: Portland
----------
Michigan's abbreviation is: MI
Florida's abbreviation is: FL
----------
Michigan has: Detroit
Florida has: Jacksonville
----------
Oregon is abbreviated OR.
Florida is abbreviated FL.
California is abbreviated CA.
New York is abbreviated NY.
Michigan is abbreviated MI.
----------
CA has the city San Francisco.
MI has the city Detroit.
FL has the city Jacksonville.
NY has the city New York.
OR has the city Portland.
----------
Oregon state is abbreviated OR and has city Portland
Florida state is abbreviated FL and has city Jacksonville
California state is abbreviated CA and has city San Francisco
New York state is abbreviated NY and has city New York
Michigan state is abbreviated MI and has city Detroit
----------
Sorry,no Texas.
The city for the state 'TX' is:Does Not Exist

對於以上程式碼我們可以知道:

字典是可以直接新增一組元素的。

設某字典變數為a={ },那麼:

a['a']='aa'

print(a)

輸出結果是{'a': 'aa'}。

需要知道的兩個概念:

①cities.items()

我們在講出答案之前,不妨動一動腦筋自行分析一下items()的作用。

這個items()用於for in迴圈裡面,我們知道,這個迴圈就是針對列表裡的元組給便利出來。

那麼items()的作用就很清晰了:

將字典以列表的形式返回可以遍歷的元組陣列。

a={'a':'aa','b':'bb','c':"cc"}
print(a)
b=a.items()
print(b)

輸出結果:

{'a': 'aa', 'b': 'bb', 'c': 'cc'}
dict_items([('a', 'aa'), ('b', 'bb'), ('c', 'cc')])

看見了嗎?

第二個輸出結果括號內的內容是[('a', 'aa'), ('b', 'bb'), ('c', 'cc')],此時字典已經轉換成了列表的形式,裡面的key:value也轉換成了元組的形式。

 

②cities.get()

我們先來看一下get()的公式用法:

 

dict.get(key, default=None)
key:字典中要查詢的鍵。
default:如果此鍵不存在,則返回default的值,其中None為預設值。

看到以上的解釋,想必大家也會恍然大悟。我們再來看看文中的程式碼:

state=states.get('Texas',None)

if not state:
print("Sorry,no Texas.")
 
 

在state中,'Texas'不存在,則返回None的值,然後滿足if的條件,則打印出“Sorry,no Texas.”

 

 

好了,關於列表和字典,我們就複習到這兒,要時刻明確清楚列表和字典的基本概念,對於今後的程式設計中是有莫大的益處的。

接下來,我們進入一個新的階段:模組、類和物件。

Python是一種面向物件程式語言,也就是OOP。

裡邊有一種叫做類(class)的結構,通過它可以做很多的事情,構造軟體。

模組

模組的概念,大家應該已經清楚了,最經典的就是:

from sys import argv

我在部落格中對這一句的解釋就是,從sys功能包中提取argv功能,這是為了方便大家理解。

現在標準的解釋應該是:從sys模組中匯入argv引數列表。

模組就是提供函式和許多變數來處理python程式碼。

可以當作一個特殊的字典,通過它們可以儲存一些Python功能和Python程式碼。

類其實和模組差不多,也是一個容器,你可以把一組函式和資料放到這個一個容器中,然後用'.'操作符來訪問它們。

現在我要建立一個學生類:

class Student(object):

    def __init__(self,name,age):

        self.name=name

        self.age=age

這樣,我就成功建立了一個學生類,這個類裡面有學生的名字資訊和年齡資訊。

__init__()函式想必大家已經很熟悉了,乾脆點說,這是建立一個有效類時,必須含有的一個函式。

這個__init__()函式將直接收集從類裡得來資料進行處理。

物件

我會很直接明瞭地給你解釋物件的意義,我們知道,物件有一個很高深的概念叫法,就是例項化。

意思就是一個建立,當你將一個類“例項化”後,你就得到了一個物件(object)。

我來用白話解釋一下:

我在上面建立了一個學生類,是不?現在,我要在這個學生類匯入一個學生的資訊,這是一個18歲的huangpaopao同學。

於是就會有student1=Student('huangpaopao',18)

這樣,我們把這個學生的資訊儲存到了變數student1中,這個變數就是一個例項化後的物件。

也就是說,物件相當於迷你匯入。物件是類裡面的一個例項。

 

現在,我放一段歌詞的類程式碼:

class Song(object):

    def __init__(self,lyrics): #__init__shi與類聯絡的定義函式
        self.lyrics=lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print(line)

happy_birthday=Song(["Happy birthday to you",
                                      "I don't want to get sued",
                                      "So I'll stop right there"])

bulls_on_parade=Song(["They rally around the family",
                                       "With pockets full of shells"])

happy_birthday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()

輸出結果:

Happy birthday to you
I don't want to get sued
So I'll stop right there
They rally around the family
With pockets full of shells

是否能看懂這段歌詞的類程式碼?首先定義兩個歌詞變數,匯入兩次歌詞類,使這兩個歌詞變數成為兩個例項化後的物件。

然後再將這兩個物件進行唱歌函式處理,使用'.'操作符。