jevans
jevans

Reputation: 399

Comparing list items and tuples

In Python 3, I'm trying to create a program which takes input from a user as 3 digit codes and converts them into items in a list. It then compares these items with the first(the 3 digit code) part of a tuple in a list of tuples and prints the whole tuple.

import shares
portfolio_str=input("Please list portfolio: ")
portfolio_str= portfolio_str.replace(' ','')
portfolio_str= portfolio_str.upper()
portfolio_list= portfolio_str.split(',')
print(portfolio_list)
print()
print('{:<6} {:<20} {:>8}'.format('Code', 'Name', 'Price'))
data=shares.EXCHANGE_DATA
for  (code, name, share_value) in data:
      if code == i in portfolio_list:
        print('{:<6} {:<20} {:>8.2f}'.format(code, name, share_value))
else:
        print("Failure")

As you can see I'm using a module called shares containing a list of tuples called EXCHANGE_DATA which is set out like this:

EXCHANGE_DATA = [('AIA', 'Auckair', 1.50),
         ('AIR', 'Airnz', 5.60),
         ('AMP', 'Amp',3.22), 
         ('ANZ', 'Anzbankgrp', 26.25),
         ('ARG', 'Argosy', 12.22),
         ('CEN', 'Contact', 11.22),
         ('CNU', 'Chorus',3.01),
         ('DIL', 'Diligent', 5.3),
         ('DNZ', 'Dnz Property', 2.33),
         ('EBO', 'Ebos', 1.1),

An exemplar input would be: AIA, AMP, ANZ

The corresponding output would be:

Code         Name         Price
AIA          Auckair      1.50
AMP          Amp          3.22
ANZ          Anzbankgrp   26.25

I'm just stuck on the for and/or if statements which I think I need.

Upvotes: 0

Views: 161

Answers (1)

Gareth Latty
Gareth Latty

Reputation: 88977

Your issue is this here:

if code == i in portfolio_list:

This doesn't make sense in Python. in checks if a given value is contained in the list, so this checks if i is in portfolio_list, then checks if code is equal to True or False (whatever i in portfolio_list returned. What you want is simply:

if code in portfolio_list:

Note that if portfolio_list could be long, it might be worth making it a set, as checking for membership in a set is significantly more efficient for large amounts of data.

Your syntax appears to be a mashup of different methodologies. You might have meant:

if any(code == i for i in portfolio_list):

However, as this is directly equivalent to code in portfolio_list, but more verbose and inefficient, it's not a good solution.

Upvotes: 1

Related Questions