切片和 for 循环

Slicing and for loops

首先,在过去的一周里,我有 <48 小时的动手键盘学习 Python。

我搜索了类似的问题,它们确实存在,但我正在寻找 introtopython.org 假设我根据我在课程中的位置知道的解决方案。 (意思是没有 f 字符串,没有条件表达式。)

打印出一系列句子,“裁判可以给体操运动员_分。”如果您的第一句话在语法上不正确,请不要担心,但如果您能用切片弄清楚它,则会加分。

我的第一次尝试代码:

# A gymnast can earn a score between 1 and 10 from each judge; nothing lower,
# nothing higher. All scores are integer values; there are no decimal scores
# from a single judge.

pscores = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
onepoint = pscores[:1]
for pscore in onepoint:
    print("\nA judge can give a gymnast ",str(onepoint)," point.")
print("A judge can give a gymnast %d points." % (pscores[1]))
print("A judge can give a gymnast %d points." % (pscores[2]))
print("A judge can give a gymnast %d points." % (pscores[3]))
print("A judge can give a gymnast %d points." % (pscores[4]))
print("A judge can give a gymnast %d points." % (pscores[5]))
print("A judge can give a gymnast %d points." % (pscores[6]))
print("A judge can give a gymnast %d points." % (pscores[7]))
print("A judge can give a gymnast %d points." % (pscores[8]))
print("A judge can give a gymnast %d points.\n" % (pscores[9]))

输出:

A judge can give a gymnast  [1]  point.
A judge can give a gymnast 2 points.
A judge can give a gymnast 3 points.
A judge can give a gymnast 4 points.
A judge can give a gymnast 5 points.
A judge can give a gymnast 6 points.
A judge can give a gymnast 7 points.
A judge can give a gymnast 8 points.
A judge can give a gymnast 9 points.
A judge can give a gymnast 10 points.

超级近。我无法弄清楚如何让第一个打印行与 %d 占位符一起显示,没有括号。此外,当我试图在 for 循环中计算分数 2-10 时,我有一个 morepoints var,但我无法让它工作(更多积分 = pscores[1:])

我觉得我即将了解如何在没有 f 字符串或条件表达式的情况下做我想做的事情(因为我还不知道如何使用它们)。

是我,还是我正在使用的特定网站让我有机会根据我对列表和元组的了解自行解决?

编辑:虽然我可以摆脱我目前拥有的 for 循环并将其替换为类似于最后 9 行的行,但我正在尝试弄清楚如何用切片和循环来压缩所有这些。

切片始终是一个列表,即使它只有一个元素。所以代码中的变量 onepoint 是包含 pscores.

中第一个元素的列表

为了获取第一个元素而不是列表,您可以获取 pscoresonepoint 的第一个索引。

score = pscores[0]  # this
scrore = onepoint[0]  # or this
print("\nA judge can give a gymnast ",str(score)," point.")

你的 for 循环不工作的原因是因为你的迭代器变量是 pscore 但你转换为字符串的变量是 onepoint。所以这也行得通:

for pscore in onepoint:
    print("\nA judge can give a gymnast ",str(pscore)," point.")

如果目标是使用切片,我认为它们可能意味着字符串的切片,下面的三行单独将得到结果:

text = "A judge can give a gymnast points."

for pscore in range(1,11):
    print(text[:-8], pscore, text[-7:])