【问题标题】:Search for unknown numbers in a txt and plot them在 txt 中搜索未知数字并绘制它们
【发布时间】:2019-08-04 14:44:47
【问题描述】:

最近,我开始使用 Python 评估一些数据。但是,评估和操作我记录的数据似乎很复杂。

例如,我的 .txt 文件包括:

1551356567 0598523403 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0    
1551356567 0598523436 0000003362 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0    
1551356567 0598523469 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0    
1551356567 0598523502 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0    
1551356567 0598523535 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0      
1551356567 0598523766 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0    
1551356567 0598523799 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0    
1551356567 0598523832 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0    
1551356567 0598523865 0000003314 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0    
1551356567 0598523898 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0    
1551356567 0598523931 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0   
1551356568 0598524756 0000003384 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0  

重要的值只有第三列(3362)和第一列(1551...),其中第三列应该是x轴,第一列是y轴。只有值不等于 0 的行是重要的。这个想法是创建一个在第三列中搜索值的循环,如果有一个值!= 0,那么这个值应该保存在 x-list (x) 中,对应的 y 值在 y-list 中(y)。

目前我读取和操作数据的脚本如下所示:

import numpy as np

rawdata = np.loadtxt("file.txt")
num_lines = sum(1 for line in open("file.txt"))

with open("file.txt") as hv:  
   line = hv.readline()

x = list()
y = list()

i = 1
j = 0
while line != num_lines:
    if rawdata[j][2] != 0:
        x = x.append(rawdata[j][2])
        y = x.append(rawdata[j][0])
    else:
        j += 1
    if i == num_lines:
        break
    i += 1

print(x)
print(y)

我认为存在一些局部和全局变量问题,但我无法解决它们,让我们说用新值“更新”我的列表。最后应该有一个列表,只有:

[3362, 3314, 3384] for x and

[1551356567, 1551356567, 1551356568] for y

您对我如何“更新”我的列表有什么建议吗?

【问题讨论】:

    标签: python python-3.x list variables import


    【解决方案1】:

    当您阅读每一行时,将其拆分为空格并将每一列转换为整数:

    x = []
    y = []
    
    with open('file.txt') as f:
        for line in f:
            data = [int(col) for col in line.split()]
            if data[2] != 0:
                x.append(data[2])
                y.append(data[0])
    
    print(x)
    print(y)
    

    输出:

    [3362, 3314, 3384]
    [1551356567, 1551356567, 1551356568]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-28
      • 2016-07-20
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      • 2013-04-27
      相关资源
      最近更新 更多