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

标签 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]

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

最佳答案

我不确定您是否真的想跟踪这些方 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/

相关文章:

python - Django - 在 models.py 中过滤查询集

python - 在 OpenCV 中从桌面获取输入流

loops - 在 OpenMP 中折叠三个 for 循环中的两个

java - 在 for 循环中解析无效游标状态

javascript - for循环跳过间隔javascript

python - 在 pandas 中处理转换为 DateTime 的时间值而无需手动迭代?

python - 对于列表中的每个点,计算到所有其他点的平均距离

python - 根据函数的输入交错列表

java - 努力理解 "List<String> list = people.stream().map(Person::getName).collect(Collectors.toList());"

python - 从 python 中的列表和字典嵌套中删除任意元素