简体   繁体   中英

How to do inputs in Python

I have to open file in Python, what looks like this:

Rapla;Tartu;157
Tallinn;Narva;211
Valga;Haapsalu;249
Viljandi;Paide;71
Tartu;Rakvere;123
Rapla;Narva;259
Paide;Narva;196
Paide;Tallinn;92

I want to get program to work like this with an example:

Please enter starting point: Rapla
Now please enter ending point: Tartu
Distance between Rapla and Tartu is 157 km.

I managed to make a list in python, but I'm fairly new in Python and I dont know, how to do inputs, so I could get a accetable output.

What I managed to do so far:

town1 = []
town2 = []
distance = []

f = open('town.csv')
for list in f:
    x = list.split(';')
    town1.append(x[0])
    town2.append(x[1])
    distance.append(x[2])

f.close()

n = len(town1)
for i in range(n):
    print('Starting point is: ' + town1[i])
    print('Ending point is:  ' + town2[i])
    print('Distance between', town1[i], 'and', town2[i], 'is', distance[i], 'km.')

Program just prints every single town starting point and ending point with distance, but I want to make program to ask me starting point and ending point.

# assumes Python 2.x
from collections import defaultdict
import csv

def load_distances(fname):
    distance = defaultdict(dict)
    with open(fname, "rb") as inf:
        incsv = csv.reader(inf, delimiter=";")
        for town_a, town_b, dist in incsv:
            distance[town_a][town_b] = int(dist)
    return distance

def main():
    distance = load_distances("town.csv")

    town_a = raw_input("Please enter starting point: ")
    town_b = raw_input("Now please enter ending point: ")
    if town_a not in distance or town_b not in distance[town_a]:
        print("I don't know how to get from {} to {}".format(town_a, town_b))
    else:
        print("Distance between {} and {} is {} km.".format(town_a, town_b, distance[town_a][town_b]))

if __name__=="__main__":
    main()

If you are using Python 3, you need to replace raw_input() with input() and open(fname, "rb") with open(fname, newline="") .

defaultdict is a special type of dict ; if you ask it for an object it doesn't have, it returns a new default object instead of causing an error.

To read user input, use the input() function. Based on the parentheses around your print() calls, I'm guessing taht you are using Python 3. Beware that input() in Python 2 works differently; input() in Python 3 is roughly equivalent to raw_input() in Python 2.

To read the data file, use the csv module with delimiter=';' .

Here is a way to do it for python 2.x using filters.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def loadTowns():
    with open('town.csv') as f:
        return [row.split(';') for row in f.read().splitlines()]

towns = loadData()

start = raw_input("Enter your start: ")
towns = filter(lambda r: r[0] == start, towns)

dest = raw_input("Enter your destination: ")
towns = filter(lambda r: r[1] == dest, towns)

print towns[0][2] if towns else "Not a valid selection"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM