【问题标题】:How do I move to the next index?如何移动到下一个索引?
【发布时间】:2012-10-29 17:22:32
【问题描述】:

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

【问题讨论】:

  • 你想要一个柜台,所以外面有i=0,里面有dividor+[i],然后是i+=1

标签: python loops indexing while-loop


【解决方案1】:

您要么需要将当前索引存储在一个变量中:

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 

【讨论】:

  • 注意:从 2.6 开始,建议调用 next(obj)(它实际上调用 obj.next()),这样可以指定默认值并避免使用 StopIteration - 例如:next(obj, None)
【解决方案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】:

    为什么不遍历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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-30
      • 2021-05-04
      • 2015-10-29
      • 2021-12-15
      • 1970-01-01
      • 2010-10-30
      • 1970-01-01
      • 2018-10-17
      相关资源
      最近更新 更多