从.txt读取3列数据到lis

2024-03-29 13:42:43 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我有个问题。我有下面的文本文件(3列和空格之间)。我想把每一列(tt,ff,ll)插入它自己的列表(time,l,f)。在

文本文件:

   0.0000000000000000     656.5342434532456082       0.9992059165961109
   1.0001828508431749     656.5342334512754405       1.0009810769697651
   2.0003657016863499     656.5342259805754566       0.9989386155502871
   3.0005485525295246     656.5342339081594218       1.0005032672779635
   4.0007314033726997     656.5342356101768928       0.9996101946453564
   5.0009142542158749     656.5342236489159404       0.9986884414684027
   6.0010971050590491     656.5342474828242985       1.0001061182847479
   7.0012799559022243     656.5342355894648563       1.0003982380731031
   8.0014628067453994     656.5342256832242356       0.9993176599964499
   9.0016456575885737     656.5342218575017341       0.9999117456245585
  10.0018285084317498     656.5342408970133192       1.0000973751521087
  11.0020113592749240     656.5342243211601954       0.9997189612768125
  12.0021942101180983     656.5342320396634932       0.9997487346699927
  13.0023770609612743     656.5342291293554808       0.9991986731183715

但我想要以下输出:

^{pr2}$

尝试代码:

from numpy import *



def read_file(filename):
   time = [] # list time
   f = [] # ...
   l = [] # ...
   infile = open(filename, "r") # reads file
   for line in infile: # each line in txt file
      numbers = line.split() # removes the " "
      tt = numbers[0] # 1st column?
      ff = numbers[1] # 2nd column?
      ll = numbers[2] # 3rd column?


      time.append(tt) # Inserts 1st column(tt) into list(time) 
      f.append(ff) # ...
      l.append(ll) # ...

return time,f,l # return lists

txt1 =read_file("1.txt") # calls function
print txt1 # print return values

Tags: readreturntimelinecolumnfilenameinfilelist
3条回答

使用numpy的loadtxt函数

text_array = np.loadtxt('my_file.txt')
time = text_array[:, 0]
l = text_array[:, 1]
f = text_array[:, 2]

我刚试过你的代码,它工作了,返回了一个列表的元组。如果您的问题是如何将这个列表元组转换为您所请求的格式(由于数据量太大,这将非常笨拙),您可以使用txt1变量将其添加到末尾:

(编辑以包括换行符)

print ("time: ({})\nl: ({})\nf: ({})".format(*[','.join(i) for i in txt1]))

这将用逗号连接每个列表,并使用解包运算符(*)将它们分隔为format函数的三个参数。在

我喜欢另一个答案,它使用numpy的功能来处理文件。也可以使用内置函数这样做(请注意,这将返回元组列表):

^{pr2}$

您的return语句当前缩进错误。当我纠正它似乎有效。在

更简单的方法可能是

def read_file(filename):
    infile = open(filename, "r") # reads file
    rows = [line.split() for line in infile]
    return [r[i] for r in rows for i in range(3)] # return lists

相关问题 更多 >