如何拼合列表? [英] How to flatten a List?

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

问题描述

如何轻松在Dart中展平列表

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的每个元素,在其上执行一个函数,该函数返回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天全站免登陆