2016-11-01 1 views
0

Для школы у меня есть задание сделать, но я не знаю, что делать.Сравнить значения в одном списке

У меня есть две станции, начало (начало) и eindStation (конец). Сначала мне нужно было проверить, есть ли они или нет в списке станций. Все прошло хорошо. Теперь, однако, я должен проверить, входит ли в тот же список eindStation после beginStation.

stations_place = {"Schagen" : 1, "Heerhugowaard" : 2, "Alkmaar" : 3, "Castricum" : 4, "Zaandam" : 5, "Amsterdam Sloterdijk" : 6, "Amsterdam Centraal" : 7, "Amsterdam Amstel" : 8, "Utrecht Centraal" : 9, "'s-Hertogenbosch" : 10, "Eindhoven" : 11, "Weert" : 12, "Roermond" : 13, "Sittard" : 14, "Maastricht" : 15} 

eindStation = str(input("What is your end station? ")) 

if eindStation in stations_place: 
    print("good") #just to check if the code does it's job here 
else : 
    print("This station isn't available, endstation is: Maastricht") 

if eindStation >= beginStation in stations_place.values: 
    print("good") #just to check if the code does it's job here 
else: 
    print("This station isn't available, endstation is: Maastricht") 

Надеюсь, вы, ребята, можете мне помочь. Заранее спасибо!

ответ

0

Я думаю beginStation также запросить у пользователя, так же, как eindStation, верно?

Если да, то вы можете сделать первую проверку, чтобы проверить также начальную станцию. например .:

if (eindStation in stations_place) and (beginStation in stations_place): 

И тогда последний если может быть:

if stations_place[eindStation] >= stations_place[beginStation]: 

Надеется, что это помогает.

2

Для начала вам необходимо указать beginStation.
Вот один из способов:

stations_place = {"Schagen" : 1, "Heerhugowaard" : 2, "Alkmaar" : 3, "Castricum" : 4, "Zaandam" : 5, "Amsterdam Sloterdijk" : 6, "Amsterdam Centraal" : 7, "Amsterdam Amstel" : 8, "Utrecht Centraal" : 9, "'s-Hertogenbosch" : 10, "Eindhoven" : 11, "Weert" : 12, "Roermond" : 13, "Sittard" : 14, "Maastricht" : 15} 
eindStation = str(input("What is your end station? ")) 

if eindStation in stations_place: 
    print("good") #just to check if the code does it's job here 
else : 
    print("This station isn't available, endstation is: Maastricht") 
beginStation = str(input("What is your Starting station? ")) 
if stations_place[eindStation] >= stations_place[beginStation]: 
    print("good") #just to check if the code does it's job here 
else: 
    print("This station isn't available, endstation is: Maastricht") 

Edit: Это> = должно быть действительно> так как никто не хочет ехать от а к а :)

0

Я не могу не думать о том, что определение stations_place в ваш код как list, а не dictionary будет лучше для ваших целей.
A list «заказывается», а dictionary - нет. В вашем случае станции упорядочены, так как они никогда не меняют позицию, поэтому выбор упорядоченной структуры данных имеет смысл.
Это облегчает жизнь, если вы хотите расширить свой код.
т.е.

stations_place = ["Schagen","Heerhugowaard","Alkmaar","Castricum","Zaandam","Amsterdam Sloterdijk", "Amsterdam Centraal","Amsterdam Amstel","Utrecht Centraal","'s-Hertogenbosch","Eindhoven","Weert","Roermond","Sittard","Maastricht"] 
result = False 
while result == False:#Keep asking until a valid start station is input 
    fromText ="" 
    for i in stations_place:#Build text station list 
     fromText += i+" > " 
    print (fromText+"\n") 
    beginStation = str(input("What is your Starting station? ")) 
    if beginStation in stations_place: 
     result = True 
    else: 
     print("This station isn't available, Starting station is:",stations_place[0],"\n")#first list item 
result = False 
while result == False:#Keep asking until a valid end station is input 
    fromS = stations_place.index(beginStation)# Get index of start station 
    fromText ="" 
    for i in stations_place[fromS:]:#Build text list of following stations 
     fromText += i+" > " 
    print (fromText+"\n") 
    eindStation = str(input("What is your end station? ")) 
    if eindStation in stations_place: 
     result = True 
    else : 
     print("This station isn't available, End station is:",stations_place[-1]+"\n")#Last list item 

if stations_place.index(eindStation) > stations_place.index(beginStation):#Check index values 
    print("Your journey is valid") 
elif stations_place.index(eindStation) == stations_place.index(beginStation):#Check index values 
    print("Your Start and End stations are the same") 
else: 
    print("Your end station is before the start station") 
    print("Use the other platform for the other direction") 

Schagen > Heerhugowaard > Alkmaar > Castricum > Zaandam > Amsterdam Sloterdijk > Amsterdam Centraal > Amsterdam Amstel > Utrecht Centraal > 's-Hertogenbosch > Eindhoven > Weert > Roermond > Sittard > Maastricht > 

What is your Starting station? Alkmaar 
Alkmaar > Castricum > Zaandam > Amsterdam Sloterdijk > Amsterdam Centraal > Amsterdam Amstel > Utrecht Centraal > 's-Hertogenbosch > Eindhoven > Weert > Roermond > Sittard > Maastricht > 

What is your end station? Zaandam 
Your journey is valid 

В качестве примечания, Рубен один из ваших одноклассников, потому что вариант этого вопроса уже на SO Python trainticket machine, так что будьте осторожны, ваш учитель может найти этот вопрос, так как это первый элемент из моей поисковой системы с запросом "python zaandam station".