Home > database >  Very basic Python confusion. How to take input from a multiple input and start array?
Very basic Python confusion. How to take input from a multiple input and start array?

Time:10-17

Hi this is a beginner code I wrote.

n = int(input())
for i in range(n):
    car, price = list(input().split())

#wanted to create cars into an array, but wrong code
for i in range(n):
    print(car[i], end = " ")`

Hi, this is a very basic doubt. I want to input the car and price in 1 line. Eg.

Audi 2
BMW 3
Ford 4

This is possible by

 for i in range(n):
    car, price = list(input().split())

But afterwards I want to group the cars and prices itself like

car = [Audi, BMW, Ford...]
prices = [2, 3, 4]

for i in range(n):
    print(car[i], end = " "). 

My understanding of this line is wrong. Please correct and kindly restructure the code to the requirement.

CodePudding user response:

You have to collect the cars and prices in lists. Initialize the lists before the loop, then add cars and prices in the loop:

n = int(input())
cars = []
prices = []
for i in range(n):
    car, price = input().split()
    cars.append(car)
    prices.append(int(price))  # convert to number

However, a better idea might be to use a dictionary, to associate cars with their prices.

n = int(input())
cars_prices = {}
for i in range(n):
    car, price = input().split()
    cars_prices[car] = int(price)

This way, you can easily get the min, max, or sorted cars by price, e.g. cheapest = min(cars_prices, key=cars_prices.get).

  • Related