gpt4 book ai didi

list - 在 Elixir 中有效压缩不等长列表

转载 作者:行者123 更新时间:2023-12-01 14:03:12 26 4
gpt4 key购买 nike

Elixir zip/2 函数压缩两个列表,当到达较短列表的末尾时停止。我一直在尝试做相反的事情——基本上是从较短的列表中复制项目,直到到达最长列表的末尾。

这是我所拥有的:

def zipReduce(m, n) when is_list(m) and is_list(n) do
{ long, short } = if length(m) > length(n)
do { m, n }
else { n, m }
end

Enum.reduce(0..Integer.mod(length(long), length(short)), [], fn i, acc ->
long
|> Enum.slice(length(short) * i, length(short))
|> Enum.zip(short)
|> Enum.into(acc)
end)
end

它确实有效,但我不喜欢所有这些对 length/1 的调用,因为每个调用都需要一个完整的列表遍历,而且它可能在相当大的缩减范围内。我可以将长度与短列表和长列表一起缓存在元组中,但这感觉非常必要(尽管必要时我会这样做以提高性能)。

有没有我没想到的方法?可能是完全不同的方法?

最佳答案

做这样的事情:

Enum.zip(Stream.cycle(short), long)

例如

iex(1)> Enum.zip(Stream.cycle([1,2,3,4]), [:a, :b, :c, :d, :e, :f, :g, :h])
[{1, :a}, {2, :b}, {3, :c}, {4, :d}, {1, :e}, {2, :f}, {3, :g}, {4, :h}]

这将在较短列表中的元素与较长列表中的数据一样多地循环。

关于list - 在 Elixir 中有效压缩不等长列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56096487/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com