0
点赞
收藏
分享

微信扫一扫

反转 Dart 列表

木匠0819 2022-08-18 阅读 92

下面的两个示例向您展示了如何在 Dart 中反转和打乱给定列表。

反转 Dart 列表

编码:

// main.dart
void main() {
final List listOne = [1, 2, 3, 4, 5, 6, 7, 8, 9];
final List listTwo = ['a', 'b', 'c', 'd'];

final List reversedListOne = listOne.reversed.toList();
print(reversedListOne);

final List reversedListTwo = listTwo.reversed.toList();
print(reversedListTwo);
}

输出:

[9, 8, 7, 6, 5, 4, 3, 2, 1]
[d, c, b, a]

对dart列表洗牌

我们可以使用shuffle()方法随机打乱列表。请注意,此方法将更改原始列表。

例子:

// main.dart
void main() {
final List listOne = [1, 2, 3, 4, 5, 6, 7, 8, 9];
final List listTwo = ['a', 'b', 'c', 'd'];

listOne.shuffle();
listTwo.shuffle();

print(listOne);
print(listTwo);
}

输出:

[5, 1, 9, 4, 2, 3, 7, 8, 6]
[b, c, a, d]

由于随机性,每次执行代码时很可能会收到不同的输出。


举报

相关推荐

0 条评论