我有2个循环:
第一个循环:
number = 1234567
number_string = str(number)
for ch in number_string:
print(ch)
这将打印:
1
2
3
4
5
6
7
我有另一个循环:
totalNum = len(str(abs(number)))
for i in range(totalNum, 0, -1):
print("* 10^ ",int(i-1))
我会得到
* 10^ 6
* 10^ 5
* 10^ 4
* 10^ 3
* 10^ 2
* 10^ 1
* 10^ 0
但是我如何加入这两个循环才能成为这样的结果:
1 * 10^ 6
2 * 10^ 5
3 * 10^ 4
4 * 10^ 3
5 * 10^ 2
6 * 10^ 1
7 * 10^ 0
我是Python的新手,所以我无法弄清楚如何做到这一点。
答案 0 :(得分:4)
这对您有何帮助:
number = 1234567
totalNum = len(str(abs(number)))
for i in range(totalNum, 0, -1):
print(str(number)[::-1][i-1] + " * 10^ ",int(i-1))
输出:
1 * 10^ 6
2 * 10^ 5
3 * 10^ 4
4 * 10^ 3
5 * 10^ 2
6 * 10^ 1
7 * 10^ 0
答案 1 :(得分:4)
有几种方法,我使用enumerate()
索引字符串:
number = 1234567
number_string = str(number)
totalNum = len(str(abs(number)))
for j,i in enumerate(range(totalNum, 0, -1)):
print(number_string[j], "* 10^ ", int(i-1))
给出:
1 * 10^ 6
2 * 10^ 5
3 * 10^ 4
4 * 10^ 3
5 * 10^ 2
6 * 10^ 1
7 * 10^ 0
enumerate()
遍历一个序列,并给出索引号(j
)和项目(i
)的元组。
答案 2 :(得分:2)
一种方法是先将字符串存储在列表中,然后打印出来:
>>> number = 1234567
>>> totalNum = len(str(abs(number)))
>>> string1 = [x for x in str(number)]
>>> string2 = ['* 10^ {}'.format(i-1) for i in range(totalNum, 0, -1)]
>>> for s1, s2 in zip(string1, string2):
... print(s1, s2)
...
1 * 10^ 6
2 * 10^ 5
3 * 10^ 4
4 * 10^ 3
5 * 10^ 2
6 * 10^ 1
7 * 10^ 0
答案 3 :(得分:1)
这可能会有所帮助。您可以使用my_named_pipe="$HOME/foobar"
mkfifo "$my_named_pipe"
while read line; do on_fifo_msg "$line"; done < ${my_named_pipe} &
zip
<强>输出:强>
number = 1234567
totalNum = len(str(abs(number)))
for v, i in zip(str(number), range(totalNum, 0, -1)):
print(v, "* 10^ ",int(i-1))