Home > database >  how can i input values of different data types in 2d list python?
how can i input values of different data types in 2d list python?

Time:09-18

I am very noob at Python. and also noob in English, Sorry. I want to input mixed data type in one line in 2d list.

n = input("how many people? : ")
data = []

for i in range(n):
    data.append(list(map(str, input("Enter name, height(cm), weight(kg) :").split())))

if i enter code

2   
John 185 80
Tom 172 71

shows me

[['John', '185', '80'],['Tom', '172', '71']]

but i want input name in str, others in int, output like this.

[['John', 185, 80],['Tom', 172, 71]]

but if i change

data.append(list(map(str, input("Enter name, height(cm), weight(kg) :").split())))

this line of str to int, i can't input name because of error. ToT

CodePudding user response:

You can use list comprehension from list data to convert its element to int if it contains numbers using str.isdigit() function. Also, note that n should be int:

n = int(input("how many people? : "))
data = []

for i in range(n):
    data.append(list(map(str, input("Enter name, height(cm), weight(kg) :").split())))

data = [[int(num) if num.isdigit() else num for num in item] for item in data]

print(data)

# how many people? : 2
# Enter name, height(cm), weight(kg) :John 185 80
# Enter name, height(cm), weight(kg) :Tom 172 71
# [['John', 185, 80], ['Tom', 172, 71]]

Or you can unpack the input value and cast the element containing numbers to int, then append the value to list:

n = input("how many people? : ")
data = []

for i in range(int(n)):
    name, height, weight = input("Enter name, height(cm), weight(kg) :").split()
    person = [name, int(height), int(weight)]
    data.append(person)

print(data)

# how many people? : 2
# Enter name, height(cm), weight(kg) :John 185 80
# Enter name, height(cm), weight(kg) :Tom 172 71
# [['John', 185, 80], ['Tom', 172, 71]]
  • Related