我想在垂直列表中的GUI应用程序中显示任意数目的字符串。
请考虑以下示例:
val names = Seq[String]("Boris", "Anna", "Markus", "Simone")
for(a <- 1 to names.size + 1; name <- names) yield new ListItem(
name,
x = 20
y = 128 * a
size = 128
)当然,这将创建一个“交叉产品”并打印:
Boris Anna Markus Simone
Boris Anna Markus Simone
Boris Anna Markus Simone
Boris Anna Markus Simone而通缉的结果是
Boris
Anna
Markus
Simone但是,否则如何将索引绑定到实际变量?我的意思是,如果我做一个柜台,比如:
for(a <- 0 to 1; b <- 0 to 1)
yield(a,b)我会得到
Vector((0,0), (0,1), (1,0), (1,1))但如果我愿意的话,我可以(for a <- 0 to 1; b <- 0 to a) yield(a,b)和
Vector((0,0), (1,0), (1,1))我不知道用我的例子怎么做。
发布于 2015-07-26 22:10:43
您需要zipWithIndex,它将创建一个新的Seq,其中包含原始Seq中的每个元素,并在Seq中使用它的索引进行元组化。
scala> names.zipWithIndex
res2: Seq[(String, Int)] = List((Boris,0), (Anna,1), (Markus,2), (Simone,3))然后,您可以使用:
val names = Seq[String]("Boris", "Anna", "Markus", "Simone")
class ListItem(name: String, x: Int, y: Int, size: Int)
scala> for ((name, index) <- names.zipWithIndex)
yield new ListItem(name, 20, 128 * index, 128)
res0: Seq[ListItem] = List(ListItem@5956b37d, ListItem@4b22015d, ListItem@2587a734, ListItem@6cf25a2b)也可以编写为map。
names.zipWithIndex.map { case (name, index) =>
new ListItem(name, 20, 128 * index, 128)
}https://stackoverflow.com/questions/31642358
复制相似问题