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

Question:

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

Asked By: Jin

||

Answers:

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]]
Answered By: Arifa Chan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.