How do I make my code discern how to divide my array?
Question:
I have to read this line from the text file:
Asta Ieva 5 0 17 10 23 23
The first two words are a name, all the others are different numbers. How do I make it so that that my program creates a list that goes like this: (name, number, number, number…)
Answers:
Start by using line.split(" ")
to break up the individual words. Then you can use str.isdigit()
to test which are names and which are numbers.
For example:
mylist = ["Number" if word.isdigit() else "Name"
for word in line.split(" ")]
If you need to split the array into names and numbers you could do something like
words = line.split(" ")
numbers = []
names = []
for word in words:
if word.isdigit():
numbers.append(int(word))
else:
names.append(word)
I have to read this line from the text file:
Asta Ieva 5 0 17 10 23 23
The first two words are a name, all the others are different numbers. How do I make it so that that my program creates a list that goes like this: (name, number, number, number…)
Start by using line.split(" ")
to break up the individual words. Then you can use str.isdigit()
to test which are names and which are numbers.
For example:
mylist = ["Number" if word.isdigit() else "Name"
for word in line.split(" ")]
If you need to split the array into names and numbers you could do something like
words = line.split(" ")
numbers = []
names = []
for word in words:
if word.isdigit():
numbers.append(int(word))
else:
names.append(word)