在Python 3中,我有一个编码如下的程序。它基本上接受来自用户的输入并根据元组列表(EXCHANGE_DATA)进行检查并输出信息列表。问题是,数据在输出时按字母顺序排序,这不是我想要的方式。我该如何解决?
from shares import EXCHANGE_DATA
portfolio_str=input("Please list portfolio: ")
portfolio_str= portfolio_str.replace(' ','')
portfolio_str= portfolio_str.upper()
portfolio_list= portfolio_str.split(',')
print()
print('{:<6} {:<20} {:>8}'.format('Code', 'Name', 'Price'))
for code, share_name, share_value in EXCHANGE_DATA:
if code in portfolio_list:
print('{:<6} {:<20} {:>8.2f}'.format(code, share_name, share_value))
示例输入:
GPG,HNZ,DIL,FRE
输出应如下:
Please list portfolio: GPG,HNZ,DIL,FRE
Code Name Price
GPG Guinnesspeat 2.32
HNZ Heartland Nz 3.85
DIL Diligent 5.30
FRE Freightway 6.71
但我明白了:
Please list portfolio: GPG,HNZ,DIL,FRE
Code Name Price
DIL Diligent 5.30
FRE Freightway 6.71
GPG Guinnesspeat 2.32
HNZ Heartland Nz 3.85
更新代码
from shares import EXCHANGE_DATA
portfolio_str=input("Please list portfolio: ")
portfolio_str= portfolio_str.replace(' ','')
portfolio_str= portfolio_str.upper()
portfolio_list= portfolio_str.split(',')
print()
print('{:<6} {:<20} {:>8}'.format('Code', 'Name', 'Price'))
EXCHANGE_DATA = {code:(share_name,share_value) for code, share_name, share_value in EXCHANGE_DATA}
for code in portfolio_list:
share_name, share_value = EXCHANGE_DATA[code]
print('{:<6} {:<20} {:>8.2f}'.format(code, share_name, share_value))
答案 0 :(得分:2)
一种方法是将EXCHANGE_DATA
转换为字典,使用code
作为关键字。然后你就可以改变你的循环了:
for code in portfolio_list:
share_name, share_value = EXCHANGE_DATA[code]
print('{:<6} {:<20} {:>8.2f}'.format(code, share_name, share_value))