0

Here is some sample code from my larger program where I am searching for countries where specific airlines fly. When I run the entire program it works fine but the countries are displayed like this:

Canada
USA
USA
Brazil
Russia
Russia
Brazil
Canada

Where I want it to display only:

USA
Brazil
Russia
Canada


def displayCountriesForAirline(airlineName, airportIDs, airportDict):
    print("Aiports serviced by", airlineName)
    for airportID in airportIDs:
        if airportID in airportDict:
            airportInfo = airportDict[airportID]
            print("\t", airportInfo[2])
Justin
  • 1
  • 1
  • 1
    If you don't care abuot duplicates or about the order, then you should not be using a `list` at all. Use a `set` instead. Or, if you really need the `list` for something else, create a `set` out of it just for the sake of printing. – zvone Nov 25 '19 at 00:53
  • Now I read the code as well ;) You dont really have a list either, but a dictionary... – zvone Nov 25 '19 at 00:55
  • 1
    Does this answer your question? [Get unique values from a list in python](https://stackoverflow.com/questions/12897374/get-unique-values-from-a-list-in-python) – neutrino_logic Nov 25 '19 at 00:55

3 Answers3

0

I think you can transfer the list to set by using set(list1).

Eric Gong
  • 107
  • 1
  • 1
  • 10
0

You can use set() for storing the country names - That way, you won't have duplicates in your output (I created some example data):

airlineName = 'My Airline'
airportIDs = [1, 1, 2, 3, 3, 4, 4]
airportDict = {
    1:['x', 'y', 'Canada'],
    2:['x', 'y', 'USA'],
    3:['x', 'y', 'Brazil'],
    4:['x', 'y', 'Russia'],
}

def displayCountriesForAirline(airlineName, airportIDs, airportDict):
    print("Aiports serviced by", airlineName)
    countries = {airportDict[airportID][2] for airportID in airportIDs if airportID in airportDict}
    for country in countries:
        print("\t", country)

displayCountriesForAirline(airlineName, airportIDs, airportDict)

Prints:

Aiports serviced by My Airline
     USA
     Russia
     Canada
     Brazil
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

You can change the list to a set like this to remove duplicates:

data = ['Canada','USA','USA','Russia','Russia','Brazil','Canada']

new_data=list(set(data))

print(new_data)
#['Brazil', 'Canada', 'Russia', 'USA']
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24