1. 程式人生 > >Python基礎知識(六)

Python基礎知識(六)

迴圈,列表,字典

在開始使用 for 迴圈之前,需要在某個位置存放迴圈的結果。最好的方法是使用列表(list),列表就是一個按順序存放東西的容器。首先我們看看如何建立列表:

hairs = ['brown', 'blond', 'red']
eyes = ['brown', 'blue', 'green']
weights = [1, 2, 3, 4]

現在我們將使用迴圈建立一些列表,然後將它們打印出來:

the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change =
[1, 'pennies', 2, 'dimes', 3, 'quarters'] # 第一個for迴圈遍歷一個列表 for number in the_count: print ("This is count %d" % number) # for迴圈遍歷一個列表 for fruit in fruits: print ("A fruit of type: %s" % fruit) # 此外,我們也可以瀏覽混合列表 # 注意,我們必須使用%r,因為我們不知道里面有什麼 for i in change: print ("I got %r" % i) # 我們還可以構建列表,首先從空列表開始 elements =
[] # 然後使用range函式執行05個計數 for i in range(0, 6): print ("Adding %d to the list." % i) # append是一個列表可以理解的函式 elements.append(i) # 現在我們也可以把它們打印出來 for i in elements: print ("Element was: %d" % i)

結果

This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
A fruit of
type: apples A fruit of type: oranges A fruit of type: pears A fruit of type: apricots I got 1 I got 'pennies' I got 2 I got 'dimes' I got 3 I got 'quarters' Adding 0 to the list. Adding 1 to the list. Adding 2 to the list. Adding 3 to the list. Adding 4 to the list. Adding 5 to the list. Element was: 0 Element was: 1 Element was: 2 Element was: 3 Element was: 4 Element was: 5

常見問題
Q: 如何定義一個兩層(2D)的列表?

就是一個列表在另一個列表裡面,比如[[1,2,3],[4,5,6]]

Q: 列表和陣列不是同一種東西嗎?

依賴於語言和實現方式。在經典設計角度,由於陣列列表的實現方式不同,陣列列表是非常不同的。在Ruby中程式設計師稱之為陣列。在Python中,他們稱之為列表。因為現在是Python呼叫它們,所以我們就稱呼它為列表。

Q: 為什麼for 迴圈可以使用一個沒有定義過的變數?

在for迴圈開始的時候,就會定義這個變數, 並初始化。

Q: 為什麼for i in range(1, 3):只迴圈了兩次?

range()函式迴圈的次數不包括最後一個。所以range(1,3)只迴圈到2,這是這種迴圈最常用的方法。

Q: elements.append()實現什麼功能?

它能實現在列表的末尾追加一個元素。開啟Python解析器,自己寫一個列表做些實驗。當你遇到這類問題的時候,都可以在Python的解析器中做些實驗,自己找到問題的答案。

while迴圈

while迴圈(while-loop)。while迴圈會一直執行它下面的程式碼片段,直到它對應的布林表示式為False時才會停下來。While 迴圈有一個問題,那就是有時它永遠不會結束。為了避免這樣的問題,你需要遵循下面的規定:

  1.儘量少用while-loop,大部分時候for-loop是更好的選擇。
  2.重複檢查你的while語句,確定你的布林表示式最終會變成False 。
  3.如果不確定,就在while迴圈的結尾打印出你測試的值。看看它的變化。
i = 0
numbers = []

while i < 6:
    print ("At the top i is %d" % i)
    numbers.append(i)

    i = i + 1
    print ("Numbers now: ", numbers)
    print ("At the bottom i is %d" % i)

print ("The numbers: ")

for num in numbers:
    print (num)

結果

At the top i is 0
Numbers now:  [0]
At the bottom i is 1
At the top i is 1
Numbers now:  [0, 1]
At the bottom i is 2
At the top i is 2
Numbers now:  [0, 1, 2]
At the bottom i is 3
At the top i is 3
Numbers now:  [0, 1, 2, 3]
At the bottom i is 4
At the top i is 4
Numbers now:  [0, 1, 2, 3, 4]
At the bottom i is 5
At the top i is 5
Numbers now:  [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers: 
0
1
2
3
4
5

常見問題
Q: for 迴圈和while迴圈有什麼區別?

for 迴圈只能對某種事物的集合做迴圈,而while可以進行任何種類的迴圈。但是,while迴圈很容易出錯,大部分情況for迴圈也是一個很好的選擇。

訪問列表元素

訪問第一個元素的方法是這樣的:

animals = ['bear', 'tiger', 'penguin', 'zebra']
bear = animals[0]

分支和函式

from sys import exit

def gold_room():
    print ("This room is full of gold.  How much do you take?")

    choice = input("> ")
    if "0" in choice or "1" in choice:
        how_much = int(choice)
    else:
        dead("Man, learn to type a number.")

    if how_much < 50:
        print ("Nice, you're not greedy, you win!")
        exit(0)
    else:
        dead("You greedy bastard!")

def bear_room():
    print ("There is a bear here.")
    print ("The bear has a bunch of honey.")
    print ("The fat bear is in front of another door.")
    print ("How are you going to move the bear?")
    bear_moved = False

    while True:
        choice = input("> ")

        if choice == "take honey":
            dead("The bear looks at you then slaps your face off.")
        elif choice == "taunt bear" and not bear_moved:
            print ("The bear has moved from the door. You can go through it now.")
            bear_moved = True
        elif choice == "taunt bear" and bear_moved:
            dead("The bear gets pissed off and chews your leg off.")
        elif choice == "open door" and bear_moved:
            gold_room()
        else:
            print ("I got no idea what that means.")

def cthulhu_room():
    print ("Here you see the great evil Cthulhu.")
    print ("He, it, whatever stares at you and you go insane.")
    print ("Do you flee for your life or eat your head?")

    choice = input("> ")

    if "flee" in choice:
        start()
    elif "head" in choice:
        dead("Well that was tasty!")
    else:
        cthulhu_room()

def dead(why):
    print (why, "Good job!")
    exit(0)

def start():
    print ("You are in a dark room.")
    print ("There is a door to your right and left.")
    print ("Which one do you take?")

    choice = input("> ")

    if choice == "left":
        bear_room()
    elif choice == "right":
        cthulhu_room()
    else:
        dead("You stumble around the room until you starve.")

start()
You are in a dark room.
There is a door to your right and left.
Which one do you take?
>  left
There is a bear here.
The bear has a bunch of honey.
The fat bear is in front of another door.
How are you going to move the bear?
>  taunt bear
The bear has moved from the door. You can go through it now.
>  open door
This room is full of gold.  How much do you take?
>  1000
You greedy bastard! Good job!

IF 語句的規則:

  1. 每一個“if 語句”必須包含一個 else.
  2. 如果這個else永遠都不應該被執行到,因為它本身沒有任何意義,那你必須在else語句後面使用一個叫做die的函式,讓它打印出錯誤資訊,這和上一節的習題類似,這樣你可以找到很多的錯誤。
  3. “if 語句”的巢狀不要超過 2 層,最好儘量保持只有 1 層。
  4. 將“if 語句”當做段落來對待,其中的每一個if-elif-else 組合就跟一個段落的句子一樣。在這種組合的最前面和最後面留一個空行以作區分。
  5. 你的布林測試應該很簡單,如果它們很複雜的話,你需要將它們的運算事先放到一個 變數裡,並且為變數取一個好名字。

迴圈的規則

  1. 只有在迴圈永不停止時使用“while迴圈”,這意味著你可能永遠都用不到。這條只有 Python 中成立,其他的語言另當別論。
  2. 其他型別的迴圈都使用“for迴圈”,尤其是在迴圈的物件數量固定或者有限的情況下。

除錯的小技巧

  1. 不要使用 “debugger”。Debugger所作的相當於對病人的全身掃描。你不會得到某方面的有用資訊,而且你會發現它輸出的資訊大部分沒有用,或者只會讓你更困惑。
  2. 最好的除錯程式的方法是使用print,在各個你想要檢查的關鍵環節將關鍵變數打印出來,從而檢查哪裡是否有錯。
  3. 讓程式一部分一部分地執行起來。不要等一個很長的指令碼寫完後才去執行它。寫一點,執行一點,修改一點。

字典

Python 將這種資料型別叫做 “dict”,有的語言裡它的名稱是 “hash”。這兩種名字我都會用到,不過這並不重要,重要的是它們和列表的區別。針對列表可以做這樣的事情:

>>> things = ['a', 'b', 'c', 'd']
>>> print things[1]
b
>>> things[1] = 'z'
>>> print things[1]
z
>>> things
['a', 'z', 'c', 'd']

可以使用數字作為列表的索引,也就是可以通過數字找到列表中的元素。現在應該瞭解列表的這些特性,也應瞭解只能通過數字來獲取列表中的元素。

而 dict 所作的,是可以通過任何東西找到元素,不只是數字。是的,字典可以將一個物件和另外一個東西關聯,不管它們的型別是什麼,我們來看看:

>>> stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2}
>>> print stuff['name']
Zed
>>> print stuff['age']
39
>>> print stuff['height']
74
>>> stuff['city'] = "San Francisco"
>>> print stuff['city']
San Francisco

你將看到除了通過數字以外,我們還可以用字串來從字典中獲取 stuff ,我們還可以用字串來往字典中新增元素。當然它支援的不只有字串,我們還可以做這樣的事情:

>>> stuff[1] = "Wow"
>>> stuff[2] = "Neato"
>>> print stuff[1]
Wow
>>> print stuff[2]
Neato
>>> stuff
{'city': 'San Francisco', 2: 'Neato', 'name': 'Zed', 1: 'Wow', 'age': 39, 'height': 74}

在這段程式碼中,使用了數字,當列印stuff的時候,可以看到,不止有數字還有字串作為字典的key。事實上,可以使用任何東西,這麼說並不準確。

當然了,一個只能放東西進去的字典是沒啥意思的,所以有刪除的方法,也就是使用del 這個關鍵字:

>>> del stuff['city']
>>> del stuff[1]
>>> del stuff[2]
>>> stuff
{'name': 'Zed', 'age': 36, 'height': 74}

一個字典例項

注意一下這個例子中是如何對應這些州和它們的縮寫,以及這些縮寫對應的州里的城市。 記住, “對映” 是字典中的關鍵概念。

# 建立狀態到縮寫的對映
states = {
    'Oregon': 'OR',
    'Florida': 'FL',
    'California': 'CA',
    'New York': 'NY',
    'Michigan': 'MI'
}

# 建立一個基本的州和一些城市的集合
cities = {
    'CA': 'San Francisco',
    'MI': 'Detroit',
    'FL': 'Jacksonville'
}

# 增加一些城市
cities['NY'] = 'New York'
cities['OR'] = 'Portland'

# 打印出一些城市
print ('-' * 10)
print ("NY State has: ", cities['NY'])
print ("OR State has: ", cities['OR'])

# 列印一些州
print ('-' * 10)
print ("Michigan's abbreviation is: ", states['Michigan'])
print ("Florida's abbreviation is: ", states['Florida'])

# 是通過州和城市的法令嗎
print ('-' * 10)
print ("Michigan has: ", cities[states['Michigan']])
print ("Florida has: ", cities[states['Florida']])

# 列印每個州的縮寫
print ('-' * 10)
for state, abbrev in states.items():
    print ("%s is abbreviated %s" % (state, abbrev))

# 在州內印刷每一個城市
print ('-' * 10)
for abbrev, city in cities.items():
    print ("%s has the city %s" % (abbrev, city))

# 現在同時做這兩件事
print ('-' * 10)
for state, abbrev in states.items():
    print ("%s state is abbreviated %s and has city %s" % (
        state, abbrev, cities[abbrev]))

print ('-' * 10)
# 安全得到一個可能不在那裡的州的縮寫
state = states.get('Texas')

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

# 獲取具有預設值的城市
city = cities.get('TX', 'Does Not Exist')
print ("The city for the state 'TX' is: %s" % city)

結果

$ python ex39.py
----------
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
----------
California is abbreviated CA
Michigan is abbreviated MI
New York is abbreviated NY
Florida is abbreviated FL
Oregon is abbreviated OR
----------
FL has the city Jacksonville
CA has the city San Francisco
MI has the city Detroit
OR has the city Portland
NY has the city New York
----------
California state is abbreviated CA and has city San Francisco
Michigan state is abbreviated MI and has city Detroit
New York state is abbreviated NY and has city New York
Florida state is abbreviated FL and has city Jacksonville
Oregon state is abbreviated OR and has city Portland
----------
Sorry, no Texas.
The city for the state 'TX' is: Does Not Exist

字典能做什麼

字典是另一個數據結構的例子,和列表一樣,是程式設計中最常用的資料結構之一。 字典是用來做對映或者儲存你需要的鍵值對,這樣當你需要的時候,你可以通過key來獲取它的值。同樣,程式設計師不會使用一個像“字典”這樣的術語,來稱呼那些不能像一個寫滿詞彙的真實字典正常使用的事物,所以我們只要把它當做真實世界中的字典來用就好。

假如你想知道這個單詞"Honorificabilitudinitatibus"的意思。你可以很簡單的把它複製貼上放進任何一個搜尋引擎中找到答案。我們真的可以說一個搜尋引擎就像一個巨大的超級複雜版本的《牛津英語詞典》(OED).在搜尋引擎出現之前,你可能會這樣做:

   1.走進圖書館,找到一本字典,我們稱這本字典為OED
   2.你知道單詞"honorificabilitudinitatibus" 以字母 'H'開頭,所以你檢視字典的小標籤,找到以 'H' 開頭的部分.
   3.然後你會瀏覽書頁,直到找到"hon"開頭的地方。
   4.然後你再翻過一些書頁,直到找到 "honorificabilitudinitatibus" 或者找到以 "hp" 開頭的單詞,發現這個詞不在我們的字典中。
   5.當你找到這個條目,你就可以仔細閱讀並弄明白它的意思。

這個過程跟我們在程式中使用字典的是相似的,你會對映(“mapping”)找到這個單詞"honorificabilitudinitatibus"的定義。Python中的字典就跟真實世界中的這本牛津詞典(OED)差不多。
定義自己的字典類

最後一段程式碼演示瞭如何使用你剛學會的list來建立一個字典資料結構。這段程式碼可能有些難以理解,所以如果你要花費你很長的時間去弄明白程式碼額含義也不要擔心。程式碼中會有一些新的知識點,它確實有些複雜,還有一些事情需要你上網查詢

為了使用Python中的dict儲存資料,我打算把我的資料結構叫做hashmap,這是字典資料結構的另一個名字。你要把下面的程式碼輸入一個叫做hashmap.py的檔案,這樣我們就可以在另一個檔案 ex39_test.py中執行它。

def new(num_buckets=256):
    """用給定的桶數初始化對映。"""
    aMap = []
    for i in range(0, num_buckets):
        aMap.append([])
    return aMap

def hash_key(aMap, key):
    """給定一個鍵,這將建立一個數字,然後將其轉換為aMap桶的索引。"""
    return hash(key) % len(aMap)

def get_bucket(aMap, key):
    """如果有一把鑰匙,就把水桶放在它要去的地方。"""
    bucket_id = hash_key(aMap, key)
    return aMap[bucket_id]

def get_slot(aMap, key, default=None):
    """返回在桶中找到的槽的索引、鍵和值。在未找到時返回-1、鍵和預設值(未設定則為None)。"""
    bucket = get_bucket(aMap, key)

    for i, kv in enumerate(bucket):
        k, v = kv
        if key == k:
            return i, k, v

    return -1, key, default

def get(aMap, key, default=None):
    """獲取桶中給定鍵或預設值的值。"""
    i, k, v = get_slot(aMap, key, default=default)
    return v

def set(aMap, key, value):
    """將鍵設定為值,替換任何現有值。"""
    bucket = get_bucket(aMap, key)
    i, k, v = get_slot(aMap, key)

    if i >= 0:
        # 這個鍵存在,替換它
        bucket[i] = (key, value)
    else:
        # 這個鍵沒有,附加建立它
        bucket.append((key, value))

def delete(aMap, key):
    """從對映中刪除給定的鍵。"""
    bucket = get_bucket(aMap, key)

    for i in xrange(len(bucket)):
        k, v = bucket[i]
        if key == k:
            del bucket[i]
            break

def list(aMap):
    """打印出地圖上的內容。"""
    for bucket in aMap:
        if bucket:
            for k, v in bucket:
                print (k, v)

上面的程式碼建立了一個叫做hashmap的模組,你需要把這個模組import到檔案 ex39_test.py 中,並讓這個檔案執行起來:

import hashmap

# 建立狀態到縮寫的對映
states = hashmap.new()
hashmap.set(states, 'Oregon', 'OR')
hashmap.set(states, 'Florida', 'FL')
hashmap.set(states, 'California', 'CA')
hashmap.set(states, 'New York', 'NY')
hashmap.set(states, 'Michigan', 'MI')

# 建立一個基本的州和一些城市的集合
cities = hashmap.new()
hashmap.set(cities, 'CA', 'San Francisco')
hashmap.set(cities, 'MI', 'Detroit')
hashmap.set
            
           

相關推薦

Python基礎知識

迴圈,列表,字典 在開始使用 for 迴圈之前,需要在某個位置存放迴圈的結果。最好的方法是使用列表(list),列表就是一個按順序存放東西的容器。首先我們看看如何建立列表: hairs = ['brown', 'blond', 'red'] eyes = ['brown', 'blu

python基礎知識

.py .com 數值類型 spa gbk 4.5 wal 編碼 nic 1.pycharm使用 快速搜索欄,蠻重要的 2.字符串格式化 %s 字符串類型 %d數值類型 msg = "我是%s,年齡%d,愛好%s" % (‘alex‘, 18, ‘boy‘) print(

python基礎知識理論

log bytes py3 utf 國標 gpo 條件 兩個 %d 一、運算符1.算數運算符 + - * / % ** //2**10 2的10次方4.2 // 2 == 2 只取整數部分,取商的整數部分py2 4.2 / 2 ==2py3

linux 基礎知識

linux 基礎知識 日誌 日誌的作用:1.解決系統方面的問題2.解決網絡服務的問題3.記錄過往事件 /var/log/ //日誌文件保存位置cron //記錄周期性任務計劃dmesg //開機核心偵測信息lastlog //系統所有行好最近一次的登陸信息mail

Python基礎知識 初識Python

快捷 err ogl 熱門 HR 會有 社區 小型 palm Python簡介 一、Python介紹 Python(英國發音:/?pa?θ?n/ 美國發音:/?pa?θɑ?n/),是一種廣泛使用的高級編程語言,屬於通用型編程語言,由吉多·範羅蘇姆創造,第一版發布於1

Python基礎知識 Python編碼、變量、if和while語句

SM 不同的 正式 網頁 end oot 循環輸出 mut 字符編碼 Python入門知識 一、第一句Python代碼 在Linux下/home/test目錄下創建hello.py文件,內容如下: [root@root ~]# mkdir /home/test [

廖雪峰網站—學習python基礎知識

style 字符串 知識 code ron sar sof 轉換 () 一、判斷 1、條件判斷 age = 18 if age >= 18: print(‘your are is‘, age) print(‘adult‘) ag

Python基礎知識

邏輯 邏輯術語 在 python 中我們會用到下面的術語(字元或者詞彙)來定義事物的真(True)或者假(False)。計算機的邏輯就是在程式的某個位置檢查這些字元或者變數組合在一起表達的結果是真是假。 and 與 or 或 not 非 != (not equal) 不等於 ==

Python基礎知識

檔案操作 1. 讀檔案 input和argv,這些是你開始學習讀取檔案的必備基礎。你可能需要多多實驗才能明白它的工作原理,所以你要細心做練習,並且仔細檢查結果。處理檔案需要非常仔細,否則,你可能會把有用的檔案弄壞或者清空。導致前功盡棄。 這節練習涉及到寫兩個檔案。一個正常的 ex

python基礎彙總

這是最後一篇python基礎彙總了。 在進入正題之前,忍不住嘮叨一句: python的前途越來越光明,隨著馬雲的無人酒店,無人海底撈陸續面世,python重要性越來越大。 未來是屬於人工智慧的,完成人工智慧的程式碼是python自動化程式碼。   我們先來複習一下列表和字典的一些基礎知識。

python基礎學習函式基礎

函式的基本使用 函式的定義 def 函式名(): 函式封裝的程式碼 …… def 是英文 define 的縮寫 函式名稱 應該能夠表達 函式封裝程式碼 的功能,方便後續的呼叫 函式名稱 的命名應該 符合 識別符號的命名規則 可以由 字母、下劃線 和

python基礎知識

集合 set 建立集合 set('zhou wu') print('z','h','o','u',' ','w','u') 集合分類 可變集合(set):可新增、刪除,非可雜湊,不能用作字典的鍵值,也不可做其他集合的元素。 不可變集合(frozenset):

Python基礎-函式

一、函式介紹   函式是組織好的,可重複使用的,用來實現單一,或相關聯功能的程式碼段。   函式能提高應用的模組性,和程式碼的重複利用率。Python提供了許多內建函式,比如print()。但你也可以自己建立函式,這被叫做使用者自定義函式。   如果在開發程式時,需要某塊程式碼多次,但是為了提高編寫的效

C++基礎知識--類--成員函式的定義--物件的建立與使用--從面向過程到面向物件

一、類   1.類是一種資料型別,將資料與對資料的操作(函式)放到一起。一個類中的資料通常只能通過本類提供的方法進行處理,這些方法成為該類與外部的介面,物件之間通過訊息進行通訊。   2.如果在類的起始點無訪問說明符,系統預設為私有(private)   3.類是一種資料型別,定義時系統不為類分配儲存空

C++基礎知識--類--成員函數的定義--對象的創建與使用--從面向過程到面向對象

物理 邏輯 需要 面向對象技術 函數 span void 成員函數 開發 一、類   1.類是一種數據類型,將數據與對數據的操作(函數)放到一起。一個類中的數據通常只能通過本類提供的方法進行處理,這些方法成為該類與外部的接口,對象之間通過消息進行通訊。   2.如果在類的起

JAVA基礎-其全面詳解Java基礎知識

101、java中會存在記憶體洩漏嗎,請簡單描述。會。如:int i,i2. return (i-i2). //when i為足夠大的正數,i2為足夠大的負數。結果會造成溢位,導致錯誤。102、java中實現多型的機制是什麼?方法的重寫Overriding和過載Overlo

PHP之新手自學基礎知識——拓展篇之名稱空間

名稱空間概述 什麼是名稱空間?從廣義上來說,名稱空間是一種封裝事物的方法。在很多地方都可以見到這種抽象概念。例如,在作業系統中目錄用來將相關檔案分組,對於目錄中的檔案來說,它就扮演了名稱空間的角色。具體舉個例子,檔案foo.txt 可以同時在目錄/home/g

Python基礎知識

post 練習 初學 查看 http 變量 規則 style python程序 首先,對於初學者在一個項目中設置多個程序可以執行,是非常方便的,可以方便對不同知識點的練習和測試 對於商業項目而言,通常在一個項目中,只有一個可以執行的Python程序 一、註釋 為了提高可讀性

Python基礎知識

break post elif true 滿足 賦值 隨機數 計數 spa 一、分支運算   在Python 2.x中判斷不等於還可以用<> if語句進階:elif if 條件1:   ...... elif 條件2:   ...... else:

Python基礎知識

內容 對象 com color define cti 判斷 函數封裝 charm 一、函數 def 函數名(): 函數封裝的代碼 ... def是英文define縮寫 別的Python文件可以引入 調用 定義時 和其他代碼包括註釋保留兩個空行