如何在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] };