1

In Python 3 I have a program coded as below. It basically takes an input from a user and checks it against a list of tuples (EXCHANGE_DATA) and outputs a list of information. The problem is, is that the data has been sorted alphabetically when it is outputted and this is not the way I want it. How do I fix it?

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

Example input: GPG,HNZ,DIL,FRE

The output should be as follows:

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

but I get:

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

UPDATED CODE

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

1 に答える 1

2

One way is to turn EXCHANGE_DATA into a dictionary, using code as the key. Then you'll be able to transform your loop like:

for code in portfolio_list:
    share_name, share_value = EXCHANGE_DATA[code]
    print('{:<6} {:<20} {:>8.2f}'.format(code, share_name, share_value))
于 2013-03-27T06:23:18.090 に答える