我有一个文本文件,其中包含一个由数字组成的表格,例如:
5 10 6
6 20 1
7 30 4
8 40 3
9 23 1
4 13 6
例如,如果我想要仅包含在第二列中的数字,我如何将该列提取到列表中?
最佳答案
f=open(file,"r")
lines=f.readlines()
result=[]
for x in lines:
result.append(x.split(' ')[1])
f.close()
您可以使用列表推导式来做同样的事情
print([x.split(' ')[1] for x in open(file).readlines()])
关于 split()
string.split(s[, sep[, maxsplit]])
Return a list of the words of the string
s
. If the optional second argument sep is absent or None, the words are separated by arbitrary strings of whitespace characters (space, tab, newline, return, formfeed). If the second argument sep is present and not None, it specifies a string to be used as the word separator. The returned list will then have one more item than the number of non-overlapping occurrences of the separator in the string.
所以,你可以省略我使用的空格,只使用 x.split()
但这也会删除制表符和换行符,请注意这一点。
关于python - 从python中的文本文件中读取特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30216573/