【发布时间】:2017-03-19 09:53:25
【问题描述】:
我有一个数字列表:
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]
我需要去掉括号,每行只需要包含一个平方值(对应于左边的整数)。我该怎么做?
【问题讨论】:
-
为什么要建立一个列表?为什么不在您创建的 first 循环中使用
print()来打印i * i结果? -
遵循第一个示例中的相同方法,并在循环中打印:
print("The square of", i, "is", i * i)。您无需在新列表中收集值。 -
我不知道为什么我没想到 - 是的,它按预期工作,谢谢!
标签: python list for-loop printing integer