for循环中相同集合的迭代器 [英] Iterators over same collection in for-loop

查看:142
本文介绍了for循环中相同集合的迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想生成Set的子集的所有组合。由于 subset 返回迭代器我不想将其转换为严格的。

Assume i want to generate all combinations of subsets of a Set. Since subset returns an iterator I don't want to convert it to something strict.

def gen(A: Set[Int]) = {
  val it0 = A.subsets
  val it1 = A.subsets
  for(a <- it0; b <- it1) yield (a,b)
}

但它不是我想要的。例如 gen(Set(1,2,3))。foreach(println)返回:

but it does not what I want. For Example gen(Set(1,2,3)).foreach(println) returns:

(Set(),Set())
(Set(),Set(1))
(Set(),Set(2))
(Set(),Set(3))
(Set(),Set(1, 2))
(Set(),Set(1, 3))
(Set(),Set(2, 3))
(Set(),Set(1, 2, 3))

似乎只有第二个迭代器迭代所有子集。为什么它表现得那样,是否有一种很好的方法可以避免这种情况?

It seems only the second iterator iterates over all subsets. Why does it behave like that and is there a nice way to avoid this?

推荐答案

注意 it0 it1 Iterator s。你不能使用这样的迭代器:

Note that it0 and it1 are Iterators. You can't use iterators like this:

val it0 = Iterator(1, 2)
val it1 = Iterator(1, 2)

(for { a <- it0; b <- it1 } yield (a, b)).toList
// List[(Int, Int)] = List((1,1), (1,2))

这里的原因是你无法重复迭代 Iterator Iterator 是可变的。对于 it0 的第一个元素,你已经迭代 it1 ,所以 it1 it0 的下一个元素,$ c>为空。

The reason here is that you can't re-iterate over Iterator, Iterator is mutable. For the first element of it0 you have iterated over it1, so it1 is empty for next elements of it0.

您应该为每个元素重新创建第二个迭代器of first iterator:

You should either re-create second iterator for every element of first iterator:

def gen(A: Set[Int]) = 
  for{
    a <- A.subsets
    b <- A.subsets
  } yield (a,b)

或将 Iterator 转移到不可变集合:

Or convet Iterator to immutable collection:

def gen(A: Set[Int]) = {
  val it = A.subsets.toSeq
  for(a <- it; b <- it) yield (a,b)
}

这篇关于for循环中相同集合的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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