[英]How do I extract the numbers from the last column in a txt file in python?
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.
例如,当代码到达第一个数字时,它会先查看“1”,然后查看“0”,然后查看“1”,并将它们分别添加为单独的数字,而不是一个数字: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).您可以使用
line.split(" ")
来做到这一点(这也会在列表中留下大量空字符串,因为有多个空格,但可以忽略它们)。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.