【问题标题】:How to loop in the opposite order?如何以相反的顺序循环?
【发布时间】:2013-12-09 19:06:00
【问题描述】:

我是一名初级程序员。这是我的代码:

n = int(input())
from math import*
for i in range(n):
    print(n, "\t", log10(n))
    i = i + 1
    n = n - 1

它的输出是:

10   1.0
9    0.9542425094393249
8    0.9030899869919435
7    0.8450980400142568    
6    0.7781512503836436
5    0.6989700043360189    
4    0.6020599913279624
3    0.47712125471966244
2    0.3010299956639812
1    0.0

我希望它是:

1    0.0
2    0.3010299956639812
3    0.47712125471966244
4    0.6020599913279624
5    0.6989700043360189
.
.
.
9    0.9542425094393249
10   1.0

【问题讨论】:

  • for i in range(n,0,-1): print i 如果你想倒退。 range(0,n,1) 继续前进。

标签: python python-3.x


【解决方案1】:

首先,您不需要增加 i,因为它是循环变量,并且依次设置为 0 到 9 中的每一个。

然后你的循环首先打印n。它从 10 开始,每次从它减去 1,所以你得到的值是按降序排列的。试试这个:

for i in range(n):
    print i+1, "\t", log10(i+1)

【讨论】:

  • n=int(input()) while n!=0: from math import* print (n,"\t",log10(n)) n=n-1
  • 您也可以使用range(1, n+1) 从 1 迭代到 n。在这里节省不了多少,但我的想法更清晰了。
【解决方案2】:

只需使用i 作为循环中的变量元素:

n=int(input())
import math

for i in range(1,n+1):
    print(i,"\t",math.log10(i))

您可以像这样在一行中执行此操作:

print('\n'.join('{}\t{}'.format(i,math.log10(i)) for i in range(1,n+1)))

最后,习惯from math import * 并不是一个好主意。使用* 会将导入模块中的所有项目带入同一个命名空间。模块中任何类似的对象或函数名称都将覆盖具有相同名称的其他函数/对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 2021-02-06
    • 2021-12-30
    相关资源
    最近更新 更多