需要从上到下而不是从下到上打印列表

时间:2019-07-16 16:40:52

标签: python-3.x

atm程序,需要保留最近5次交易的历史记录。更新,但在底部而不是顶部显示最近的交易。

transactions在程序的开头是一个空列表,从空开始并在使用程序时填充。

if option == 5:
    if len(transactions) <=0:
        print("No History")
    if len(transactions) > 5:
        lower_bound = int(len(transactions)) - 5
        upper_bound = lower_bound + 5
        transaction_counter = 1
    for element in range(lower_bound, upper_bound):
        print(str(transaction_counter) + transactions[element])
        transaction_counter = transaction_counter + 1
  else:
       transaction_counter = 1
       for element in range(0, int(len(transactions))):
           print(str(transaction_counter) + transactions[element])
           transaction_counter = transaction_counter + 1

实际输出:

  1. 存入200美元作为存款
  2. 将5美元存入支票
  3. 将200美元从支票转为储蓄
  4. 从储蓄中提取20美元
  5. 余额查询

预期输出: 1.余额查询 2.从存款中提取$ 20 3.从支票转帐200美元到储蓄 4.将$ 5存入支票 5.将$ 200存入储蓄额

1 个答案:

答案 0 :(得分:2)

停止使用索引,自己使用元素:

w = "withddraw"
d = "deposit"
t = "transfer"
i = "inquire"
sv = "savings"
ch = "checking"

hist = []
hist.append( (i,))
hist.append( (i,))
hist.append( (d, 200, sv))
hist.append( (d, 5, ch))
hist.append( (t, 200, ch, sv))
hist.append( (w, 20, sv))
hist.append( (i,))

print(hist)

for num,what in enumerate(hist[-5:][::-1],1):
    print(num, what)

输出:

# the list 
[('inquire',), ('inquire',), ('deposit', 200, 'savings'), 
 ('deposit', 5, 'checking'), ('transfer', 200, 'checking', 'savings'), 
 ('withddraw', 20, 'savings'), ('inquire',)]

# the output of sliced last 5 reversed elements
1 ('inquire',)
2 ('withddraw', 20, 'savings')
3 ('transfer', 200, 'checking', 'savings')
4 ('deposit', 5, 'checking')
5 ('deposit', 200, 'savings')

解释列表切片以使最后5个元素反转:

hist[-5:]              # takes the last 5 elememnts of your list == the last 5 actions
hist[-5:][::-1]        # reverses the last 5 elements
enumerate(.., 1)       # enumerates the iterable starting at 1 returning tuples (num, elem)

,然后print将其输出...