1

我有一个不同钞票的列表,我想在每个循环之后跳到下一个索引。我怎样才能做到这一点?我想在第一个循环之后使 str 除数等于 [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]
4

3 回答 3

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
于 2012-10-29T20:22:33.853 回答
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 
于 2012-10-29T17:25:17.770 回答
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
于 2012-10-29T17:26:31.967 回答