python - 从python中的文本文件中读取特定列

标签 python list text-files

我有一个文本文件,其中包含一个由数字组成的表格,例如:

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/

相关文章:

python - 如何在返回值中获取列表的一部分

python - 在python中将MMM YY转换为日期时间

python - 值错误 : Series lengths must match to compare when matching dates in Pandas

python - 如何使用 cx_Freeze 安装 Python Windows 服务?

python - 在包含两个元素的列表中按项目表示

c# - 如何在 C# 中将列表中的元素数保存为变量?

c - C中的结构体和指针

python - 使用正则表达式搜索和捕获字符 Python

r - 如何将两行移动到 R 列表中数据框的顶部?

python - 在 Python 2.7.3 中使用正则表达式搜索文本并输出匹配项