lua - Lua - 分析文本文件中的值
问题描述
我正在将功率(瓦特)值写入文本文件以提取我可以使用的信息。
4.7
4.7
4.8
5.2
5.1
4.6
4.6
4.6
目前我有以下代码可以给我平均值,但我想添加它,以便它告诉我更多信息,例如最高值、最低值、最频繁值是什么,以及如果可能的话记录了任何“0”值(* - 如果可能,最后一个值最好忽略它们..)
local ctr = 0
local sum = 0
for _ in io.lines"/www/EnergyPlug-b.txt" do
ctr = ctr + 1
end
print(ctr)
for line in io.lines"/www/EnergyPlug-b.txt" do
sum = sum + line
end
print(sum)
average = sum / ctr
print(average)
table.insert()
我确实探索了通过第一部分创建 Lua 表io.lines
,如下所示,但我不确定它有多好?
local rows = {}
-- go over the file line by line
for line in io.lines("/www/EnergyPlug-b.txt") do
-- if line matches ?.? then insert into table
local value = line:match("%d%p%d") -- 1.5
--print(value)
table.insert(rows, value)
end
local arraymax = math.max(unpack(rows))
local arraymin = math.min(unpack(rows))
print (arraymax) -- ?.?
print (arraymin) -- ?.?
如果上述情况合适,我应该如何最好地确定我一开始提到的项目/价值?
解决方案
在第一个片段中,没有理由为 ctr 和 sum 设置单独的循环。您可以在一个循环中完成。
你的第二次剪断没问题。unpack
是有限的,因此这不适用于数千个值。
无论如何,您都必须遍历表以获取其他值,这样您也可以在没有该大小限制的情况下确定该循环中的最小值和最大值。
local value = line:match("%d%p%d")
如果该文件中只有这些数字,您可以在此处跳过模式匹配。
计算非常简单。我不确定你在这里挣扎什么。
local min = math.huge -- use a value that is definitely bigger than any value
local max = -math.huge -- use a value that is definitely smaller than any value
local counts = {} -- an emtpy table we'll use to count how often each value occurs
local numIngored = 0 -- how many 0 values have we ignored?
for line in io.lines(yourFileName) do
-- convert string to a number
local value = tonumber(line)
-- if we take the value into account
if value ~= 0.0 then
-- update min and max values
min = value < min and value or min
max = value > max and value or max
-- update counts
counts[value] = counts[value] and counts[value] + 1 or 1
else
-- count ignored values
numIgnored = numIgnored + 1
end
end
我会留给你来获取最常见的值counts
推荐阅读
- java - 动态多 cron 表达式的 Spring 启动计划
- r - 如何按多列/变量分组
- react-native - 从 Expo React Native 获取设备序列号
- node.js - Google Sheets API 导致 Node 中出现“GoogleAuth 不是构造函数”错误
- c++ - 如何将位置存储在数组中并用于以后在 C++ 中?
- jsf - 通过未封装的selectOneMenu显示表单
- python-3.x - TypeError:不能在类似字节的对象正则表达式上使用字符串模式,没有获得标准
- javascript - 在 React 中,是否可以更改 map 方法内部的状态,如果不能,有什么替代方法?
- python - 如果子表中的值发生变化,则更新父表的最后修改时间
- tensorflow-datasets - tensorflow 数据集找到了不同版本的请求数据集