面向非程序员的 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 之间时才为真(换句话说,如果您在代数中见过,它就是您所期望的)。
列表可以被认为是一系列盒子。每个盒子都有不同的值。例如,由 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
扩展 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: ")