Flashield's Blog

Just For My Daily Diary

Flashield's Blog

Just For My Daily Diary

04.exercise-lists【练习:列表】

This notebook is an exercise in the Python course. You can reference the tutorial at this link.


Try It Yourself

Things get more interesting with lists. See if you can solve the questions below. Remember to run the following cell first.

自己尝试一下

有了列表,事情就变得更有趣了。 看看你能否解决下面的问题。 请记住首先运行以下单元格。

from learntools.core import binder; binder.bind(globals())
from learntools.python.ex4 import *
print('Setup complete.')
Setup complete.

Exercises

练习

1.

Complete the function below according to its docstring.

1.

根据文档字符串完成下面的函数。

def select_second(L):
    """Return the second element of the given list. If the list has no second
    element, return None.
    返回给定列表的第二个元素。 如果列表中没有第二个元素,返回 None。
    """
    #pass
    return L[1] if len(L) >= 2 else None

# Check your answer
q1.check()

Correct

#q1.hint()
q1.solution()

Solution:

def select_second(L):
    if len(L) < 2:
        return None
    return L[1]

2.

You are analyzing sports teams. Members of each team are stored in a list. The Coach is the first name in the list, the captain is the second name in the list, and other players are listed after that.
These lists are stored in another list, which starts with the best team and proceeds through the list to the worst team last. Complete the function below to select the captain of the worst team.

2.

您正在分析运动队。 每个团队的成员都存储在一个列表中。 教练是列表中的第一个名字,队长是列表中的第二个名字,其他球员列在后面。
这些列表存储在另一个列表中,该列表从最好的团队开始,一直到最差的团队。 完成下面的函数来选择最差队伍的队长

def losing_team_captain(teams):
    """Given a list of teams, where each team is a list of names, return the 2nd player (captain)
    from the last listed team
    给定一个球队列表,其中每个球队都是一个名字列表,返回排在最后的球队中第二名球员(队长)
    """
    #pass
    return teams[-1][1]

# Check your answer
q2.check()

Correct

#q2.hint()
q2.solution()

Solution:

def losing_team_captain(teams):
    return teams[-1][1]

3.

The next iteration of Mario Kart will feature an extra-infuriating new item, the Purple Shell. When used, it warps the last place racer into first place and the first place racer into last place. Complete the function below to implement the Purple Shell's effect.

3.

《马里奥赛车》的下一个版本将推出一个格外令人恼火的新物品,紫贝壳。 使用时,它会将最后一名赛车手调换为第一名,并将第一名赛车手调换为最后一名。 完成下面的函数来实现紫贝壳的效果。

def purple_shell(racers):
    """Given a list of racers, set the first place racer (at the front of the list) to last
    place and vice versa.

    给定一个赛车手列表,将第一名赛车手(列表前面)设置为最后一名,反之亦然。

    >>> r = ["Mario", "Bowser", "Luigi"]
    >>> purple_shell(r)
    >>> r
    ["Luigi", "Bowser", "Mario"]
    """
    # pass
    racers[0], racers[-1] = racers[-1], racers[0]

# Check your answer
q3.check()

Correct

#q3.hint()
q3.solution()

Solution:

def purple_shell(racers):
    # One slick way to do the swap is x[0], x[-1] = x[-1], x[0].
    temp = racers[0]
    racers[0] = racers[-1]
    racers[-1] = temp

4.

What are the lengths of the following lists? Fill in the variable lengths with your predictions. (Try to make a prediction for each list without just calling len() on it.)

4.

以下列表的长度是多少? 用您的预测填写变量长度。 (尝试对每个列表进行预测,无需仅调用len()。)

a = [1, 2, 3]
b = [1, [2, 3]]
c = []
d = [1, 2, 3][1:]

# Put your predictions in the list below. Lengths should contain 4 numbers, the
# first being the length of a, the second being the length of b and so on.
lengths = [3,2,0,2]

# Check your answer
q4.check()

Correct:

  • a: There are three items in this list. Nothing tricky yet.
  • b: The list [2, 3] counts as a single item. It has one item before it. So we have 2 items in the list
  • c: The empty list has 0 items
  • d: The expression is the same as the list [2, 3], which has length 2.
# line below provides some explanation
q4.solution()

Solution:

  • a: There are three items in this list. Nothing tricky yet.
  • b: The list [2, 3] counts as a single item. It has one item before it. So we have 2 items in the list
  • c: The empty list has 0 items
  • d: The expression is the same as the list [2, 3], which has length 2.

5. 🌶️

We're using lists to record people who attended our party and what order they arrived in. For example, the following list represents a party with 7 guests, in which Adela showed up first and Ford was the last to arrive:

party_attendees = ['Adela', 'Fleda', 'Owen', 'May', 'Mona', 'Gilbert', 'Ford']

A guest is considered 'fashionably late' if they arrived after at least half of the party's guests. However, they must not be the very last guest (that's taking it too far). In the above example, Mona and Gilbert are the only guests who were fashionably late.

Complete the function below which takes a list of party attendees as well as a person, and tells us whether that person is fashionably late.

5. 🌶️

我们使用列表来记录参加我们聚会的人员以及他们到达的顺序。例如,以下列表代表一个有 7 位客人的聚会,其中 Adela 最先出现,Ford 最后到达:

 party_attendees = ['阿德拉'、'弗莱达'、'欧文'、'梅'、'莫娜'、'吉尔伯特'、'福特']

如果一位客人比聚会上至少一半的客人迟到,则被认为是时尚迟到。 然而,他们一定不能是最后一位客人(这太过分了)。 在上面的例子中,莫娜和吉尔伯特是唯一时髦迟到的客人。

完成下面的函数,获取聚会参加者和某人的列表,并告诉我们该人是否迟到。

def fashionably_late(arrivals, name):
    """Given an ordered list of arrivals to the party and a name, return whether the guest with that
    name was fashionably late.
    给定参加聚会的有序名单和姓名,返回该客人是否符合时尚迟到。
    """
    #pass
    return True if name in arrivals[(len(arrivals)+1)//2:-1] else False

# Check your answer
q5.check()

Correct

#q5.hint()
q5.solution()

Solution:

def fashionably_late(arrivals, name):
    order = arrivals.index(name)
    return order >= len(arrivals) / 2 and order != len(arrivals) - 1

Keep Going

That's it for lists and tuples! Now you have the baseline knowledge to learn about loops, which is where lists and tuples get really interesting.

继续前进

这就是列表和元组! 现在您已经掌握了了解循环的基础知识,这就是列表和元组真正有趣的地方。


04.exercise-lists【练习:列表】

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top