list Dart:创建一个从 0 到 N 的列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37798397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dart: create a list from 0 to N
提问by Cequiel
How can I create easily a range of consecutive integers in dart? For example:
如何在 dart 中轻松创建一系列连续整数?例如:
// throws a syntax error :)
var list = [1..10];
回答by Alexandre Ardhuin
You can use the List.generate constructor:
您可以使用List.generate 构造函数:
var list = new List<int>.generate(10, (i) => i + 1);
You can alternativelly use a generator:
您也可以使用生成器:
/// 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]
}
回答by Maryan
回答by David Rees
You can also use Dart's Iterable.generate function to create a range between 0..n-1
您还可以使用 Dart 的 Iterable.generate 函数来创建介于 0..n-1 之间的范围
var list = Iterable<int>.generate(10).toList()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
回答by Pacane
As far as I know there's no native equivalent way of doing this in Dart. However you can create your own Range
class, or use https://pub.dartlang.org/packages/rangeif you don't mind the dependency.
据我所知,在 Dart 中没有本地等效的方法。但是,您可以创建自己的Range
类,或者如果您不介意依赖关系,则使用https://pub.dartlang.org/packages/range。
Olov Lassus wrote an articleabout implementing your own Range class a while back
Olov Lassus 不久前写了一篇关于实现你自己的 Range 类的文章
edit: an even better way I just thought of:
编辑:我刚刚想到的更好的方法:
Iterable<int> range(int low, int high) sync* {
for (int i = low; i < high; ++i) {
yield i;
}
}
void main() {
for(final i in range(1, 20)) {
print(i);
}
}
回答by alexanderhurst
I have been using a modified version of Alexandre Ardhuin's which tries to mimic the range() provided by python Edit: found out optional positional arguments are a thing updated code below
我一直在使用 Alexandre Ardhuin's 的修改版本,它试图模仿 python 提供的 range()编辑:发现可选位置参数是下面更新的代码
range(int stop, {int start: 0, int step: 1}){
if (step == 0)
throw Exception("Step cannot be 0");
return start < stop == step > 0
? List<int>.generate(((start-stop)/step).abs().ceil(), (int i) => start + (i * step))
: [];
}
Example Usage:
示例用法:
range(16, start:-5, step: 8);
// [-5, 3, 11]
range(5);
// [0, 1, 2, 3, 4]
Unfortunately I have not entirely mimicked the easier syntax of python (range(start, stop[, step])) as dart doesn't have operator overloading or optional positional arguments.
不幸的是,我没有完全模仿 python (range(start, stop[, step])) 更简单的语法,因为 dart 没有运算符重载或可选的位置参数。
Another option using list comprehension which resembles Maryan's solution
使用类似于 Maryan 解决方案的列表理解的另一种选择
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)]
: [];
}
Example Usage:
示例用法:
listCompRange(0, 5, 1);
// [0, 1, 2, 3, 4]
I benchmarked both of these options with the following methods
我使用以下方法对这两个选项进行了基准测试
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;
}
which yielded these results slightly favoring the generator.
产生的这些结果略微有利于生成器。
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
however when I changed the function to generate from -10 to -30 with a step of -2 the results slightly favored the list comprehension.
但是,当我将函数从 -10 更改为 -30 并以 -2 为步长生成时,结果稍微有利于列表理解。
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
Updated code with positional rather than named parameters
使用位置参数而不是命名参数更新代码
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))
: [];
}
Usage: range(int a, [int stop, int step])
用法:range(int a, [int stop, int step])
If stop is not included a becomes stop and start will default to 0 If a and stop are both provided a becomes start if not provided step will default to 1 or -1 depending on whether start or stop is larger
如果不包含停止,则变为停止,开始将默认为 0 如果同时提供了 a 和停止,则变为开始,如果未提供,则步骤将默认为 1 或 -1,具体取决于 start 或 stop 是否更大
range(4);
// [0, 1, 2, 3]
range(4, 10);
// [4, 5, 6, 7, 8, 9]
range(4, 10, 2);
// [4, 6, 8]
range(-4);
// [0, -1, -2, -3]
range(10, 4);
// [10, 9, 8, 7, 6, 5]
range(10,10);
// []
range(1, 2, -1);
// []
range(x, y, 0);
// Exception
回答by Ber
There are many Python-like iterators defined in the Quiverpackage.
Quiver包中定义了许多类似 Python 的迭代器。
For example, use the range()
function:
例如,使用range()
函数:
import 'package:quiver/iterables.dart';
print(range(10).toList().toString());
Output:
输出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
It also works fine in for
loops:
它在for
循环中也能正常工作:
for (var i in range(1, 11))
print('$i');
Lots of other useful iteratorsare also provided.
还提供了许多其他有用的迭代器。