我有一个不同的货币笔记列表,我想在每个循环后跳转到下一个索引。我怎样才能做到这一点?我想在第一个循环之后将str dividor equel设为[1],然后是[2],然后是[3]等。
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]
答案 0 :(得分:0)
您需要将当前索引存储在变量中:
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
或者您可以使用迭代器:
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
答案 1 :(得分:0)
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
答案 2 :(得分:0)
为什么不循环遍历money_list
数组?
无论如何,我猜你想要能够输入一笔钱,并在变化中获得等价物?
以下是我的表现方式:
#!/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(",")
然后从终端;
$ ./change.py 1234
£12.34 = 1 x £10, 1 x £2, 1 x 20p, 1 x 10p, 2 x 2p
或确实和数量
$ ./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