[英]How to print (join) 2 loops' result
I have 2 loops: 我有2个循环:
The first loop: 第一个循环:
number = 1234567
number_string = str(number)
for ch in number_string:
print(ch)
This will print: 这将打印:
1
2
3
4
5
6
7
I have another loop which is: 我有另一个循环,它是:
totalNum = len(str(abs(number)))
for i in range(totalNum, 0, -1):
print("* 10^ ",int(i-1))
and I will get 我会的
* 10^ 6
* 10^ 5
* 10^ 4
* 10^ 3
* 10^ 2
* 10^ 1
* 10^ 0
But how do I join these 2 loops to become the result like this: 但是我如何加入这两个循环来成为这样的结果:
1 * 10^ 6
2 * 10^ 5
3 * 10^ 4
4 * 10^ 3
5 * 10^ 2
6 * 10^ 1
7 * 10^ 0
I am new to Python, so I couldn't figure out how to do that. 我是Python的新手,所以我无法弄清楚如何做到这一点。
How does this work for you: 这对你有什么用处:
number = 1234567
totalNum = len(str(abs(number)))
for i in range(totalNum, 0, -1):
print(str(number)[::-1][i-1] + " * 10^ ",int(i-1))
Output: 输出:
1 * 10^ 6
2 * 10^ 5
3 * 10^ 4
4 * 10^ 3
5 * 10^ 2
6 * 10^ 1
7 * 10^ 0
Several ways to do this, mine uses enumerate()
to index the string: 有几种方法,我使用
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))
Gives: 得到:
1 * 10^ 6
2 * 10^ 5
3 * 10^ 4
4 * 10^ 3
5 * 10^ 2
6 * 10^ 1
7 * 10^ 0
enumerate()
iterates through a sequence and gives a tuple of the index number ( j
) and the item ( i
). enumerate()
遍历一个序列,并给出索引号( j
)和项( i
)的元组。
One way, is to store the strings in a list first, then print them: 一种方法是首先将字符串存储在列表中,然后打印它们:
>>> 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
This might help. 这可能有所帮助。 You can use
zip
你可以使用
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))
Output: 输出:
1 * 10^ 6
2 * 10^ 5
3 * 10^ 4
4 * 10^ 3
5 * 10^ 2
6 * 10^ 1
7 * 10^ 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.