gpt4 book ai didi

Python - For 循环在单独的行上打印每个数字及其平方

转载 作者:行者123 更新时间:2023-12-01 03:35:19 28 4
gpt4 key购买 nike

我有一个数字列表:

nums = [12, 10, 32, 3, 66, 17, 42, 99, 20]

我的第一个任务是在新行上打印每个数字,如下所示:

12
10
32
3
66
17
42
99
20

我可以通过创建一个打印列表中整数的 for 循环来做到这一点:

nums = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for i in nums:
print(i)

现在我需要编写另一个 for 循环,在新行上打印每个数字及其正方形,如下所示:

The square of 12 is 144
The square of 10 is 100
The square of 32 is 1024
The square of 3 is 9
The square of 66 is 4356
The square of 17 is 289
The square of 42 is 1764
The square of 99 is 9801
The square of 20 is 40

到目前为止,我实际上已经能够打印平方值,但无法将它们单独放在单独的行上。我还需要去掉值周围的括号。

我的尝试:

nums = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for i in nums:
print(i)

squared = [ ]

for i in nums:
squared.append(i * i)
print("The square of", i, "is", squared)

结果:

12
10
32
3
66
17
42
99
20
The square of 12 is [144]
The square of 10 is [144, 100]
The square of 32 is [144, 100, 1024]
The square of 3 is [144, 100, 1024, 9]
The square of 66 is [144, 100, 1024, 9, 4356]
The square of 17 is [144, 100, 1024, 9, 4356, 289]
The square of 42 is [144, 100, 1024, 9, 4356, 289, 1764]
The square of 99 is [144, 100, 1024, 9, 4356, 289, 1764, 9801]
The square of 20 is [144, 100, 1024, 9, 4356, 289, 1764, 9801, 400]

我需要去掉括号,并且每行只需要包含一个平方值(与左边的整数相对应)。我该怎么做?

最佳答案

我不确定您是否真的想跟踪这些方 block ,或者这只是您打印它们的努力的一部分。

假设您确实想要跟踪方 block ,一个小的变化是:

https://repl.it/GLmw

nums = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for i in nums:
print(i)

squared = [ ]

for i in nums:
sqr = i * i
squared.append(sqr)
print("The square of {} is {}".format(i, sqr))

这使您可以准备好使用当前的方 block ,而无需从数组中引用它。

如果您确实想引用数组中的平方值,则可以使用负索引从数组末尾获取:

https://repl.it/GLms

nums = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for i in nums:
print(i)

squared = [ ]

for i in nums:
squared.append(i*i)
print("The square of {} is {}".format(i, squared[-1]))

关于Python - For 循环在单独的行上打印每个数字及其平方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40441725/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com