如何在Dart中将列表转换为地图 [英] How to convert a List into a Map in Dart

查看:86
本文介绍了如何在Dart中将列表转换为地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种现成的方式将列表转换为Dart中的地图。

I looking for an on-the-shelf way to convert a List into a Map in Dart.

例如在python中,您可以做到:

In python for example you can do:

l= [ ('a',(1,2)), ('b',(2,3)), ('c',(3,4) ) ]
d=dict(l)
==> {'a': (1, 2), 'c': (3, 4), 'b': (2, 3)}

dict函数需要一个夫妇列表。对于每对夫妇,第一个元素用作键,第二个元素用作数据。

The dict function expects a List of couple. For each couple, the first element is used as the key and the second as the data.

在Dart中,我看到了List的以下方法: asMap( ,但它没有达到我的期望:它使用列表索引作为键。
我的问题:

In Dart I saw the following method for a List : asMap(), but it's not doing what i expect: it use the list index as key. My questions:


  • 您是否知道Dart库中的任何功能?

  • 如果没有,是否有计划在核心库中添加这样的功能?

建议:

List.toMap() //same as python dict.
List.toMap( (value) => [ value[0], value[1] ] ) //Using anonymous function to return a key and a value from a list item.

感谢和问候,

尼古拉斯

推荐答案

您可以使用 Map.fromIterable

var result = Map.fromIterable(l, key: (v) => v[0], value: (v) => v[1]);

collection-for (从Dart 2.3开始):

or collection-for (starting from Dart 2.3):

var result = { for (var v in l) v[0]: v[1] };

这篇关于如何在Dart中将列表转换为地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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