用 Linkbot 學習 Python 3/列表
您已經見過儲存單個值的普通變數。但是,其他變數型別可以儲存多個值。這些被稱為容器,因為它們可以包含多個物件。最簡單的型別稱為列表。以下是一個使用列表的示例
which_one = int(input("What month (1-12)? "))
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December']
if 1 <= which_one <= 12:
print("The month is", months[which_one - 1])
以及一個輸出示例
What month (1-12)? 3 The month is March
在這個示例中,months 是一個列表。months 透過以下程式碼行定義: months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 和 'August', 'September', 'October', 'November', 'December'](請注意,也可以使用 \ 來拆分長行,但在本例中沒有必要,因為 Python 足夠智慧,可以識別括號內的所有內容都屬於一起)。[ 和 ] 用逗號 (,) 分隔列表項,開始和結束列表。該列表在 months[which_one - 1] 中使用。列表包含從 0 開始編號的項。換句話說,如果您想要 January,則使用 months[0]。給列表一個數字,它將返回儲存在該位置的值。
語句 if 1 <= which_one <= 12: 只有在 which_one 在 1 到 12 之間(包含 1 和 12)時才為真(換句話說,如果您在代數中見過它,它就是您所期望的)。
列表可以被認為是一系列盒子。每個盒子都有不同的值。例如,由 demolist = ['life', 42, 'the universe', 6, 'and', 9] 建立的盒子將如下所示
| 盒子編號 | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| demolist | "life" | 42 | "the universe" | 6 | "and" | 9 |
每個盒子都由它的編號引用,因此語句 demolist[0] 將獲取 'life',demolist[1] 將獲取 42,依此類推,直到 demolist[5] 獲取 9。
下一個示例只是為了展示列表可以執行的許多其他操作(我這一次不希望您輸入它,但您應該在互動模式下玩弄列表,直到您對它們感到滿意為止)。下面是
demolist = ["life", 42, "the universe", 6, "and", 9]
print("demolist = ",demolist)
demolist.append("everything")
print("after 'everything' was appended demolist is now:")
print(demolist)
print("len(demolist) =", len(demolist))
print("demolist.index(42) =", demolist.index(42))
print("demolist[1] =", demolist[1])
# Next we will loop through the list
for c in range(len(demolist)):
print("demolist[", c, "] =", demolist[c])
del demolist[2]
print("After 'the universe' was removed demolist is now:")
print(demolist)
if "life" in demolist:
print("'life' was found in demolist")
else:
print("'life' was not found in demolist")
if "amoeba" in demolist:
print("'amoeba' was found in demolist")
if "amoeba" not in demolist:
print("'amoeba' was not found in demolist")
another_list = [42,7,0,123]
another_list.sort()
print("The sorted another_list is", another_list)
輸出為
demolist = ['life', 42, 'the universe', 6, 'and', 9] after 'everything' was appended demolist is now: ['life', 42, 'the universe', 6, 'and', 9, 'everything'] len(demolist) = 7 demolist.index(42) = 1 demolist[1] = 42 demolist[ 0 ] = life demolist[ 1 ] = 42 demolist[ 2 ] = the universe demolist[ 3 ] = 6 demolist[ 4 ] = and demolist[ 5 ] = 9 demolist[ 6 ] = everything After 'the universe' was removed demolist is now: ['life', 42, 6, 'and', 9, 'everything'] 'life' was found in demolist 'amoeba' was not found in demolist The sorted another_list is [0, 7, 42, 123]
這個示例使用了許多新函式。請注意,您可以直接 print 整個列表。接下來,使用 append 函式將新項新增到列表的末尾。len 返回列表中包含的項數。列表的有效索引(如可以在 [] 內使用的數字)範圍從 0 到 len - 1。index 函式指示項在列表中的第一個位置。請注意,demolist.index(42) 返回 1,當執行 demolist[1] 時,它返回 42。要在互動式 Python 直譯器中獲取列表提供的所有函式的幫助,請鍵入 help(list)。
行 # Next we will loop through the list 只是對程式設計師的提醒(也稱為註釋)。Python 忽略 # 後當前行上的所有內容。接下來是這些行
for c in range(len(demolist)):
print('demolist[', c, '] =', demolist[c])
建立一個名為 c 的變數,它從 0 開始並遞增,直到達到列表的最後一個索引。同時,print 語句打印出列表的每個元素。
執行上述操作的更好的方法是
for c, x in enumerate(demolist):
print("demolist[", c, "] =", x)
del 命令可用於從列表中刪除給定元素。接下來的幾行使用 in 運算子來測試元素是否在列表中或不在列表中。sort 函式對列表進行排序。如果需要按從小到大或按字母順序排序的列表,這將非常有用。請注意,這會重新排列列表。總而言之,對於列表,將執行以下操作
| 示例 | 說明 |
|---|---|
demolist[2]
|
訪問索引 2 處的元素 |
demolist[2] = 3
|
將索引 2 處的元素設定為 3 |
del demolist[2]
|
刪除索引 2 處的元素 |
len(demolist)
|
返回 demolist 的長度 |
"value" in demolist
|
如果"value"是 demolist 中的元素,則為True |
"value" not in demolist
|
如果 "value" 不是 demolist 中的元素,則為True |
another_list.sort()
|
對 another_list 進行排序。請注意,列表必須全部是數字或全部是字串才能進行排序。 |
demolist.index("value")
|
返回 "value" 首次出現的索引 |
demolist.append("value")
|
在列表末尾新增元素 "value" |
demolist.remove("value")
|
從 demolist 中刪除 value 的第一個出現位置(與 del demolist[demolist.index("value")] 相同) |
下一個示例以更實用的方式使用這些特性
menu_item = 0
namelist = []
while menu_item != 9:
print("--------------------")
print("1. Print the list")
print("2. Add a name to the list")
print("3. Remove a name from the list")
print("4. Change an item in the list")
print("9. Quit")
menu_item = int(input("Pick an item from the menu: "))
if menu_item == 1:
current = 0
if len(namelist) > 0:
while current < len(namelist):
print(current, ".", namelist[current])
current = current + 1
else:
print("List is empty")
elif menu_item == 2:
name = input("Type in a name to add: ")
namelist.append(name)
elif menu_item == 3:
del_name = input("What name would you like to remove: ")
if del_name in namelist:
# namelist.remove(del_name) would work just as fine
item_number = namelist.index(del_name)
del namelist[item_number]
# The code above only removes the first occurrence of
# the name. The code below from Gerald removes all.
# while del_name in namelist:
# item_number = namelist.index(del_name)
# del namelist[item_number]
else:
print(del_name, "was not found")
elif menu_item == 4:
old_name = input("What name would you like to change: ")
if old_name in namelist:
item_number = namelist.index(old_name)
new_name = input("What is the new name: ")
namelist[item_number] = new_name
else:
print(old_name, "was not found")
print("Goodbye")
以下是一部分輸出
-------------------- 1. Print the list 2. Add a name to the list 3. Remove a name from the list 4. Change an item in the list 9. Quit Pick an item from the menu: 2 Type in a name to add: Jack Pick an item from the menu: 2 Type in a name to add: Jill Pick an item from the menu: 1 0 . Jack 1 . Jill Pick an item from the menu: 3 What name would you like to remove: Jack Pick an item from the menu: 4 What name would you like to change: Jill What is the new name: Jill Peters Pick an item from the menu: 1 0 . Jill Peters Pick an item from the menu: 9 Goodbye
這是一個很長的程式。讓我們看一下原始碼。行 namelist = [] 使變數 namelist 成為一個沒有專案(或元素)的列表。下一條重要的行是 while menu_item != 9:。這行程式碼開始一個迴圈,允許該程式的菜單系統。接下來的幾行顯示一個選單並確定要執行程式的哪個部分。
這一部分
current = 0
if len(namelist) > 0:
while current < len(namelist):
print(current, ".", namelist[current])
current = current + 1
else:
print("List is empty")
遍歷列表並列印每個名稱。len(namelist) 指示列表中包含多少個專案。如果 len 返回 0,則列表為空。
然後,在幾行之後,出現了語句 namelist.append(name)。它使用 append 函式將一個專案新增到列表的末尾。向下跳兩行,注意這段程式碼
item_number = namelist.index(del_name)
del namelist[item_number]
這裡使用 index 函式來查詢稍後將用於刪除專案的索引值。del namelist[item_number] 用於刪除列表中的一個元素。
下一部分
old_name = input("What name would you like to change: ")
if old_name in namelist:
item_number = namelist.index(old_name)
new_name = input("What is the new name: ")
namelist[item_number] = new_name
else:
print(old_name, "was not found")
使用 index 查詢 item_number,然後將 new_name 放置到 old_name 所在的位置。
恭喜,掌握了列表後,您現在已經足夠了解這種語言,可以執行計算機所能執行的任何計算(這在技術上被稱為圖靈完備性)。當然,仍然有很多功能可以使您的工作更輕鬆。
test.py
## This program runs a test of knowledge
# First get the test questions
# Later this will be modified to use file io.
def get_questions():
# notice how the data is stored as a list of lists
return [["What color is the daytime sky on a clear day? ", "blue"],
["What is the answer to life, the universe and everything? ", "42"],
["What is a three letter word for mouse trap? ", "cat"]]
# This will test a single question
# it takes a single question in
# it returns True if the user typed the correct answer, otherwise False
def check_question(question_and_answer):
# extract the question and the answer from the list
# This function takes a list with two elements, a question and an answer.
question = question_and_answer[0]
answer = question_and_answer[1]
# give the question to the user
given_answer = input(question)
# compare the user's answer to the tester's answer
if answer == given_answer:
print("Correct")
return True
else:
print("Incorrect, correct was:", answer)
return False
# This will run through all the questions
def run_test(questions):
if len(questions) == 0:
print("No questions were given.")
# the return exits the function
return
index = 0
right = 0
while index < len(questions):
# Check the question
#Note that this is extracting a question and answer list from the list of lists.
if check_question(questions[index]):
right = right + 1
# go to the next question
index = index + 1
# notice the order of the computation, first multiply, then divide
print("You got", right * 100 / len(questions),\
"% right out of", len(questions))
# now let's get the questions from the get_questions function, and
# send the returned list of lists as an argument to the run_test function.
run_test(get_questions())
值 True 和 False 分別指向 1 和 0。它們通常用於健全性檢查、迴圈條件等。您稍後將詳細瞭解這一點(第 布林表示式 章)。請注意,get_questions() 本質上是一個列表,因為即使它在技術上是一個函式,但返回列表的列表是它唯一的功能。
示例輸出
What color is the daytime sky on a clear day? green Incorrect, correct was: blue What is the answer to life, the universe and everything? 42 Correct What is a three letter word for mouse trap? cat Correct You got 66 % right out of 3
LinkbotMelody.py
我們還可以建立自己的專案列表,並使用 for 迴圈來迴圈遍歷它們。讓我們嘗試製作一個鍵盤按鍵列表,以按順序播放它們,以演奏一個簡單的曲調。我們將使用以下知識編寫這個程式:中央 C 是鍵盤上的第 40 個鍵。當您執行此程式時,它應該演奏一個非常熟悉的曲調的開頭。您能猜出是什麼嗎?
import barobo
dongle = barobo.Dongle()
dongle.connect()
robot = dongle.getLinkbot('6wbn') # Replace '6wbn' with the serial ID on your Linkbot
import time # Need to "import time" so we can use time.sleep()
myNotes = [44, 42, 40, 42, 44, 44, 44] # Put some notes into a list
t=0.5 # Set a value to be used for the duration of the note
for i in myNotes: # Select which keys on a piano keyboard to use for the tones
k=pow(2,(i-49)/12)*440 # Determines the frequency of the note to be played
robot.setBuzzerFrequency(k) # Directs the Linkbot to play this frequency
time.sleep(t) # Pauses the program while the note is played
robot.setBuzzerFrequency(0) # Turns off the piezo speaker at the end of each note
擴充套件 test.py 程式,使其具有一個選單,提供以下選項:進行測試、檢視問題和答案列表以及退出。此外,新增一個新問題: “真正先進的機器會發出什麼聲音?”,答案為“ping”。
擴充套件 test.py 程式,使其具有一個選單,提供以下選項:進行測試、檢視問題和答案列表以及退出。此外,新增一個新問題: “真正先進的機器會發出什麼聲音?”,答案為“ping”。
## This program runs a test of knowledge
questions = [["What color is the daytime sky on a clear day? ", "blue"],
["What is the answer to life, the universe and everything? ", "42"],
["What is a three letter word for mouse trap? ", "cat"],
["What noise does a truly advanced machine make?", "ping"]]
# This will test a single question
# it takes a single question in
# it returns True if the user typed the correct answer, otherwise False
def check_question(question_and_answer):
# extract the question and the answer from the list
question = question_and_answer[0]
answer = question_and_answer[1]
# give the question to the user
given_answer = input(question)
# compare the user's answer to the testers answer
if answer == given_answer:
print("Correct")
return True
else:
print("Incorrect, correct was:", answer)
return False
# This will run through all the questions
def run_test(questions):
if len(questions) == 0:
print("No questions were given.")
# the return exits the function
return
index = 0
right = 0
while index < len(questions):
# Check the question
if check_question(questions[index]):
right = right + 1
# go to the next question
index = index + 1
# notice the order of the computation, first multiply, then divide
print("You got", right * 100 / len(questions),
"% right out of", len(questions))
#showing a list of questions and answers
def showquestions():
q = 0
while q < len(questions):
a = 0
print("Q:" , questions[q][a])
a = 1
print("A:" , questions[q][a])
q = q + 1
# now let's define the menu function
def menu():
print("-----------------")
print("Menu:")
print("1 - Take the test")
print("2 - View a list of questions and answers")
print("3 - View the menu")
print("5 - Quit")
print("-----------------")
choice = "3"
while choice != "5":
if choice == "1":
run_test(questions)
elif choice == "2":
showquestions()
elif choice == "3":
menu()
print()
choice = input("Choose your option from the menu above: ")