Python - 用于在单独的行上打印每个数字及其正方形的循环

时间:2016-11-05 18:27:16

标签: python list for-loop printing integer

我有一个数字列表:

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]

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

3 个答案:

答案 0 :(得分:2)

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

假设您确实想要跟踪正方形,则会发生微小变化:

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))

这使您可以准备好使用当前方块,而无需从阵列中引用它。

如果您真的想从数组中引用平方值,那么您将使用负索引从数组的末尾获取:

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]))

答案 1 :(得分:1)

nums = (12, 10, 32, 3, 66, 17, 42, 99, 20)

for i in nums:
    print(i)

for i in nums:
    print("the square of",i,"is", i**2)

答案 2 :(得分:0)

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