如何展平一个列表? [英] How to flatten a List?

查看:15
本文介绍了如何展平一个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Dart 中轻松展平 List?

How can I easily flatten a List in Dart?

例如:

var a = [[1, 2, 3], ['a', 'b', 'c'], [true, false, true]];
var b = [1, 2, 3, 'a', 'b', 'c', true, false, true];

如何将 a 转换为 b,即转换为包含所有这些值的单个 List?

How do I turn a into b, i.e. into a single List containing all those values?

推荐答案

我所知道的最简单的方法是将 Iterable.expand() 与标识函数一起使用.expand() 获取 Iterable 的每个元素,对其执行一个函数,返回一个可迭代对象(expand"部分),然后连接结果.在其他语言中,它可能被称为 flatMap.

The easiest way I know of is to use Iterable.expand() with an identity function. expand() takes each element of an Iterable, performs a function on it that returns an iterable (the "expand" part), and then concatenates the results. In other languages it may be known as flatMap.

因此,通过使用标识函数, expand 只会连接项目.如果你真的想要一个列表,那么使用 toList().

So by using an identity function, expand will just concatenate the items. If you really want a List, then use toList().

var a = [[1, 2, 3], ['a', 'b', 'c'], [true, false, true]];
var flat = a.expand((i) => i).toList();

这篇关于如何展平一个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆