var list = new List<int>.generate(10, (i) => i + 1);
你也可以选择使用发电机:
/// the list of positive integers starting from 0
Iterable<int> get positiveIntegers sync* {
int i = 0;
while (true) yield i++;
}
void main() {
var list = positiveIntegers
.skip(1) // don't use 0
.take(10) // take 10 numbers
.toList(); // create a list
print(list); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
listCompRange(int start, int stop, int step) {
if (step == 0)
throw Exception("Step cannot be 0");
if (start == stop)
return [];
bool forwards = start < stop;
return forwards == step > 0
? forwards
? [for (int i = 0; i*step < stop-start; i++) start + (i * step)]
: [for (int i = 0; i*step > stop-start; i++) start + (i * step)]
: [];
}
示例用法:
listCompRange(0, 5, 1);
// [0, 1, 2, 3, 4]
我用以下方法对这两个选项进行了基准测试
benchMarkRange(){
List<List<int>> temp = List<List<int>>();
Stopwatch timer = Stopwatch();
timer.start();
for (int i = 0; i < 500; i++){
temp.add(range(-30, start: -10, step: -2));
}
timer.stop();
print("Range function\n${timer.elapsed}\n");
return temp;
}
benchMarkListComprehension(){
List<List<int>> temp = List<List<int>>();
Stopwatch timer = Stopwatch();
timer.start();
for (int i = 0; i < 500; i++){
temp.add(listCompRange(-10, -30, -2));
}
timer.stop();
print("List comprehension\n${timer.elapsed}\n");
return temp;
}
这些结果稍微有利于发电机。
Range function
0:00:00.011953
0:00:00.011558
0:00:00.011473
0:00:00.011615
List comprehension
0:00:00.016281
0:00:00.017403
0:00:00.017496
0:00:00.016878
然而,当我将函数的生成步骤从 -10改为 -30时,结果略微有利于列表内涵。
List comprehension
0:00:00.001352
0:00:00.001328
0:00:00.001300
0:00:00.001335
Range function
0:00:00.001371
0:00:00.001466
0:00:00.001438
0:00:00.001372
使用位置参数而不是命名参数更新代码
range(int a, [int stop, int step]) {
int start;
if (stop == null) {
start = 0;
stop = a;
} else {
start = a;
}
if (step == 0)
throw Exception("Step cannot be 0");
if (step == null)
start < stop
? step = 1 // walk forwards
: step = -1; // walk backwards
// return [] if step is in wrong direction
return start < stop == step > 0
? List<int>.generate(((start-stop)/step).abs().ceil(), (int i) => start + (i * step))
: [];
}
用法: range (int a,[ int stop,int step ])
如果没有包含 stop,那么将变为 stop,start 将默认为0
如果 a 和 stop 都被提供,则 a 成为 start
如果没有提供步骤将默认为1或 -1,这取决于是开始还是停止较大