在 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))