问题
I have a list of different monetary notes and I want to jump to the next index after each loop. How can I do that? I want to make the str dividor equel to [1] after the first loop, then [2], then [3] etc.
money_list = [100,50,20,10,5,1,0.5]
dividor = money_list[0]
while change>0.5:
print (change/100) + " X " + [0]
change
dividor + [0]
回答1:
You either need to store the current index in a variable:
money_list = [100,50,20,10,5,1,0.5]
cur_index = 0
while change>0.5:
print (change/100) + " X " + money_list[cur_index]
change
cur_index = cur_index + 1
Or you could use an iterator:
money_list = [100,50,20,10,5,1,0.5]
money_iterator = iter(money_list)
while change>0.5:
try:
dividor = money_iterator.next()
except StopIteration:
break
print (change/100) + " X " + dividor
change
回答2:
money_list = [100,50,20,10,5,1,0.5]
counter = 0
while change>0.5:
dividor = money_list[counter]
print (change/100) + " X " + money_list[counter])
change
counter+=1
回答3:
why not loop over the money_list
array?
in any case, i'm guessing you want to be able to input an amount of money, and be given the equivalent in change?
Here's how i'd do it:
#!/usr/bin/python
#coding=utf-8
import sys
#denominations in terms of the sub denomination
denominations = [5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1]
d_orig = denominations[:]
amounts = [ int(amount) for amount in sys.argv[1:] ]
for amount in amounts:
denominations = [[d] for d in d_orig[:]]
tmp = amount
for denomination in denominations:
i = tmp / denomination[0]
tmp -= i * denomination[0]
denomination.append(i)
s = "£" + str(amount / 100.0) + " = "
for denomination in denominations:
if denomination[1] > 0:
if denomination[0] >= 100:
s += str(denomination[1]) + " x £" + str(denomination[0] / 100) + ", "
else:
s += str(denomination[1]) + " x " + str(denomination[0]) + "p, "
print s.strip().strip(",")
and then from the terminal;
$ ./change.py 1234
£12.34 = 1 x £10, 1 x £2, 1 x 20p, 1 x 10p, 2 x 2p
or indeed and number of numbers
$ ./change.py 1234 5678 91011
£12.34 = 1 x £10, 1 x £2, 1 x 20p, 1 x 10p, 2 x 2p
£56.78 = 1 x £50, 1 x £5, 1 x £1, 1 x 50p, 1 x 20p, 1 x 5p, 1 x 2p, 1 x 1p
£910.11 = 18 x £50, 1 x £10, 1 x 10p, 1 x 1p
来源:https://stackoverflow.com/questions/13126594/how-do-i-move-to-the-next-index