开始使用免费开始使用

不使用循环计算宝可梦总分与均分

一个包含 720 只宝可梦的列表已加载为 names。对应的每只宝可梦的统计数据已作为一个 NumPy 数组加载为 statsstats 的每一行对应 names 中的一只宝可梦,每一列分别表示单项能力值(依次为 HPAttackDefenseSpecial AttackSpecial DefenseSpeed)。

您希望汇总每只宝可梦的总能力值(即 stats 中每一行的和)以及平均能力值(即 stats 中每一行的均值),以便找出最强的宝可梦。

下面的 for 循环用于收集这些数值:

poke_list = []

for pokemon,row in zip(names, stats):
    total_stats = np.sum(row)
    avg_stats = np.mean(row)
    poke_list.append((pokemon, total_stats, avg_stats))

本练习是课程的一部分

高效编写 Python 代码

查看课程

练习说明

  • 使用 NumPy 替换上面的 for 循环:
    • 使用 .sum() 方法并指定正确的轴,创建总分数组(total_stats_np)。
    • 使用 .mean() 方法并指定正确的轴,创建均分数组(avg_stats_np)。
    • names 列表、total_stats_np 数组和 avg_stats_np 数组合并,创建最终输出列表(poke_list_np)。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Create a total stats array
total_stats_np = ____.____(axis=____)

# Create an average stats array
avg_stats_np = ____

# Combine names, total_stats_np, and avg_stats_np into a list
poke_list_np = [*____(names, total_stats_np, avg_stats_np)]

print(poke_list_np == poke_list, '\n')
print(poke_list_np[:3])
print(poke_list[:3], '\n')
top_3 = sorted(poke_list_np, key=lambda x: x[1], reverse=True)[:3]
print('3 strongest Pokémon:\n{}'.format(top_3))
编辑并运行代码