Reverse loop inside a loop with same list
num = list(str(1234567))
for n1 in num:
print(n1)
for n2 in开发者_如何转开发 reversed(num):
print('\t', n2)
On each iteration, it prints the first digit from the first loop and all 7 from the reverse loop. How can I print not all digits but only the last (i.e first) digit from reverse loop?
Thanks
Simplest way is to just zip the forward and reverse lists together:
for n1, n2 in zip(num, reversed(num)):
print(n1, '\t', n2)
Here's a feeble attempt. Is this the kind of thing you're looking for?
for idx,i in enumerate(x):
print(i,"\t",x[-(idx+1)])
Do you mean like this?
num = list(str(1234567))
for i in range(len(num)):
print(num[i], '\t', num[-(i+1)])
Output is:
1 7
2 6
3 5
4 4
5 3
6 2
7 1
Nothing to do with Python, but here it is in Haskell :)
myDie = [1,2,3,4,5,6]
sevens = [ (x,y) | x <- myDie, y <- myDie, x+y == 7]
You should make a second list:
>>> num_rev = num[:]
>>> num_rev.reverse()
>>> num_rev
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Then do something like:
>>> for n1,n2 in zip(num,num_rev):
... print(n1, n2)
...
0 9
1 8
2 7
3 6
4 5
5 4
6 3
7 2
8 1
9 0
精彩评论