如何从包含map元素的list中提取author和text对应的值
操作思路
直接遍历列表中的每个Map元素,按key取值即可,不同常用编程语言的实现代码如下:
1. Python 实现
# 遍历打印每一条的作者和名言 for quote in quotes: author = quote["author"] text = quote["text"] print(f"作者:{author},名言:{text}") # 若需要把取出的结果整理为新列表 extract_list = [{"author": q["author"], "text": q["text"]} for q in quotes]
2. Dart(Flutter)实现
// 基础遍历取值 for (var quote in quotes) { String author = quote["author"]; String text = quote["text"]; print("作者:$author,名言:$text"); } // 规范开发建议:先转成实体类再使用 class Quote { final String author; final String text; Quote({required this.author, required this.text}); factory Quote.fromMap(Map map) { return Quote( author: map["author"] ?? "", text: map["text"] ?? "" ); } } // 批量转换为实体类列表 List<Quote> quoteObjs = quotes.map((e) => Quote.fromMap(e)).toList();
3. JavaScript 实现
// 遍历取值 quotes.forEach(quote => { const author = quote.author const text = quote.text console.log(`作者:${author},名言:${text}`) }) // 提取为新数组 const result = quotes.map(({author, text}) => ({author, text}))
注意事项
如果不能保证每个Map元素都一定存在author和text两个key,建议先做判空处理,避免取值时报空指针/键不存在的异常。
内容的提问来源于stack exchange,提问作者GAURAV JOSHI
相关产品推荐
相关产品推荐

