存储多个值的变量

你已经看到过存储单个值的普通变量。然而,其他类型的变量可以存储多个值。这些类型的变量被称为容器,因为它们可以包含多个对象。最简单的容器类型是列表。以下是使用列表的示例:

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]
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])

# 接下来,我们将循环遍历列表
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]

这个例子展示了很多新函数的用法。你可以直接打印整个列表。接下来,使用 append 函数将一个新项添加到列表的末尾。len 函数返回列表中项的数量。有效的索引(即可以在 [] 内使用的数字)范围是从 0 到 len - 1index 函数会返回列表中指定项的首次出现位置。例如,demolist.index(42) 返回 1,而 demolist[1] 返回 42。要查看列表提供的所有函数,可以在交互式 Python 解释器中输入 help(list)

遍历列表

以下代码会遍历列表并打印出每个元素:

for c in range(len(demolist)):
    print('demolist[', c, '] =', demolist[c])

这行代码创建了一个变量 c,它从 0 开始,直到到达列表的最后一个索引。期间,print 语句会打印出列表中的每个元素。

一个更好的方法是使用 enumerate 函数:

for c, x in enumerate(demolist):
    print("demolist[", c, "] =", x)

删除元素

del 命令可以用来删除列表中的指定元素。接下来的几行代码使用 in 运算符来测试某个元素是否在列表中或不在列表中。sort 函数用于对列表进行排序,这在你需要按照从小到大的顺序或字母顺序排列列表时非常有用。请注意,这会改变列表的顺序。

总结

对于列表,以下操作是常见的:

  • 创建和访问列表:列表使用方括号 [] 创建,元素通过索引访问。
  • 添加元素:使用 append 将元素添加到列表末尾。
  • 获取列表长度:使用 len() 获取列表的元素数量。
  • 查找元素的索引:使用 index() 查找某个元素在列表中的位置。
  • 遍历列表:可以使用 for 循环遍历列表的元素。
  • 删除元素:使用 del 删除列表中的元素。
  • 检查元素是否存在:使用 innot 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) 也能正常工作
            item_number = namelist.index(del_name)
            del namelist[item_number]
            # 上面的代码只删除第一个出现的名字
            # 以下代码可以删除所有出现的名字
            # 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 查找元素的索引值,然后将 new_name 替换 old_name

恭喜你,通过掌握了列表的使用,你现在已经掌握了足够的语言知识,可以做任何计算机能做的计算(这在技术上被称为图灵完备性)。当然,仍然有许多功能可以帮助你更轻松地编写程序。

示例

这个程序运行一个知识测试

## 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
 
最后修改: 2025年02月2日 星期日 22:11