scala - 摆脱 Scala 列表中的迭代器
问题描述
当前情况: 我正在使用组合方法来创建列表元素的所有可能组合。
//Input list
lf : List[(Char, Int)] = List((a,2), (a,1), (b,2), (b,1))
//For loop
for (len <- (0 to lf.length).toList) yield {lf.combinations(len)}
//> res1: List[Iterator[List[(Char, Int)]]] = List(non-empty iterator, non-empty
//| iterator, non-empty iterator, empty iterator, empty iterator)
组合返回Iterator[List[A]]
我需要的
- 项目清单
List[List[(Char, Int)]]
- 忽略空迭代器
我怎样才能摆脱迭代器?
解决方案
获取所有combinations()
,从单个元素到完整的List
,在一个List
.
lf.indices.flatMap(x => lf.combinations(x+1)).toList
//res0: List[List[(Char, Int)]] = List(
// List((a,2)), List((a,1)), List((b,2)), List((b,1))
// , List((a,2), (a,1)), List((a,2), (b,2)), List((a,2), (b,1)), List((a,1), (b,2)), List((a,1), (b,1)), List((b,2), (b,1))
// , List((a,2), (a,1), (b,2)), List((a,2), (a,1), (b,1)), List((a,2), (b,2), (b,1)), List((a,1), (b,2), (b,1))
// , List((a,2), (a,1), (b,2), (b,1)))
推荐阅读
- swift - 将 ASP.net 密码哈希转换为字符串 swift
- r - 有没有办法根据例如 R 中的性别来改变顶点的颜色?
- c++ - 如何在串口上实现防碰撞
- python - Python:读取 CSV 文件选择列并创建多个文本文件
- python - Python for 循环:正确实现多处理
- android - 无论设备或系统时间如何,如何获取当前时间?
- javascript - ReactJS 中 props 是如何传递的
- java - 执行失败:java.io.IOException:无法运行程序“powershell”:CreateProcess error=2,系统找不到指定的文件
- javascript - 如何使用单元格的应用程序脚本将 Google 表格数据验证添加到列中,以仅允许输入颜色和十六进制颜色代码
- mysql - MySQL - 根据日期列计算过去十二个月内另一个表中的实例