I have a file that looks like this (the last column has more or less space in between the previous one randomly):
Name LastName Age
Adrian Smith 101
Martin Ville 82
Mary Morre 9
I want to extract only the ages so I can put them inside a set.
I have tried this so far but I only get random one digit numbers:
age = set()
for line in f:
for i in line:
if i.isdigit():
age.update(i)
You are getting one digit numbers because you only check one digit at a time. For example, when the code reaches the first number, it will first look at "1", then "0" and then "1", and add them each as individual numbers, rather than one number: 101.
It would be easier to split each line into a list of each word in the line, and then add the last word in the list to your set. You could do that with line.split(" ")
(which would also leave you with a load of empty strings in the list since there are multiple spaces, but they can be ignored).
age = set()
for idx, line in enumerate(f):
if idx == 0: # ignore first line
continue
line = line.split(" ")
number = int(line[-1])
age.add(number)
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.