Scala 方法将可迭代的每个元素与另一个可迭代的每个元素组合起来?
如果我有这个:
val a = Array("a ","b ","c ")
val b = Array("x","y")
我想知道是否存在这样的方法,它可以让我遍历第一个集合,并对于它的每个元素,遍历整个第二个集合。例如,如果我们采用数组 a
,我们将有 a,x
,a,y
,b,x,<代码>b,y,<代码>c,x,<代码>c,y。我知道 zip 但据我所知它只适用于相同大小的集合,并且它关联来自相同位置的元素。
If I have this:
val a = Array("a ","b ","c ")
val b = Array("x","y")
I would like to know if such a method exists which would let me traverse the first collection, and for each of it's elements, walk the entire second collection. For example, if we take the array a
, we would have a,x
,a,y
,b,x
,b,y
,c,x
,c,y
. I know of zip but from what I've seen it only works on collections of the same sizes, and it associates elements from same positions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不确定“方法”,但这可以用嵌套/复合
for
来表达:快乐编码。
I'm not sure of a "method", but this can be expressed with just a nested/compound
for
:Happy coding.
对于未知数量的列表、不同长度的列表以及可能不同类型的列表,您可以使用以下方法:
您可以调用它,
但也可以使用不同类型的列表来调用它:
数组必须转换为列表,并且如果不能使用列表,结果将转换回数组。
更新:
在走向惰性集合的过程中,我做了一个从索引(从 0 到组合大小 - 1)到该位置结果的函数映射,可以使用模和除法轻松计算,只需要一点集中
:使用 long 甚至 BigInt 都没有问题。
更新2、迭代器:
For a list of a unknown number of lists, of different length, and for maybe different types, you can use this:
You would call it
but can call it with Lists of different kind too:
Arrays have to be converted to Lists, and the result converted back to Arrays, if you can't use Lists.
update:
On the way towards a lazy collection, I made a functional mapping from an index (from 0 to combination-size - 1) to the result at that position, easily calculated with modulo and division, just a bit concentration is needed:
It's no problem to use a long instead, or even BigInt.
update 2, The iterator:
我在我的代码中广泛使用以下内容。请注意,这适用于任意数量的列表。它创建一个迭代器而不是集合,因此您不必将潜在的巨大结果存储在内存中。
任何改进都是非常受欢迎的。
因此,使用这个迭代器,您必须编写 new CombinationIterator(List(a,b)) 来获取遍历每个组合的迭代器。
编辑:基于用户未知的版本
请注意,以下版本不是最佳的(性能方面):
。
I'm using the following extensively in my code. Note that this is working for an arbitrary number of lists. It is creating an Iterator instead of a collection, so you don't have to store the potentially huge result in memory.
Any improvements are very welcome.
So using this one, you have to write
new CombinationIterator(List(a,b))
to obtain an iterator that goes through every combination.Edit: based on user unkown's version
Note that the following version is not optimal (performance wise):
.
如果你想展示你对更高种类类型和范畴论的深入了解,你可以写:
除此之外,我更喜欢 pst 的解决方案......
If you want to show off your deep knowledge of higher kinded types and category theory, you can write:
Other than that I would prefer pst's solution...
这是另一个与 @ziggystar 的上次编辑相同的事情,但不使用列表的索引访问。
还有含糖版本:
Here's one more that does the same thing as @ziggystar's last edit but doesn't use indexed access of lists.
And the sugary version: