我有一个非常大的文本文件,其中包含超过100,000行。我需要收集/跳过一定数量的行:循环通过行1-100,跳过行101-150,读取行151-210,跳过行211-300(例如)。
我有以下代码
$lines = file('file.txt');
$counter = 0;
foreach ($lines as $lineNumber => $line) {
$counter++;
if ($counter < 101) {
//Do update stuff
}
if ($counter < 102 && $counter > 151) {
//Skip these lines
}
if ($counter < 152 && $counter > 211) {
//Do update stuff
}
}
有没有更好的方法可以跳过阵列输出的多行?
答案 0 :(得分:2)
首先,转到#include <iostream>
#include <functional>
#include <tuple>
#include <vector>
int main()
{
std::tuple<
std::vector<std::function<void()>>,
std::vector<std::function<void(int)>>
> functionTuple;
// We use push_back in this example, since we deal with vectors.
std::get<0>(functionTuple).push_back([](){
std::cout << "Function without arguments." << std::endl;
});
std::get<1>(functionTuple).push_back([](int arg){
std::cout << "Function without int as argument. Arg = " << arg << std::endl;
});
std::get<1>(functionTuple).push_back([](int arg){
std::cout << "Another function without int as argument. Arg = " << arg << std::endl;
});
std::get<0>(functionTuple).front()();
int i = 5;
// And we use foreach, to loop over all functions which take one integer as argument
for(auto& f : std::get<1>(functionTuple)) {
f(i);
i += 5;
}
return 0;
}
,这是内存效率的方式。您不需要将所有数组都放在内存中。至于条件,只需将所有条件与fgets
运算符结合使用,不添加跳过条件,它就没用了。
or
P.S。你的条件有误,if ($counter < 101 || ($counter >= 151 && $counter <= 210) || add another pediods here) {
//Do update stuff
}
总是($counter < 102 && $counter > 151)
和另一个。{/ p>