Closed. This question needs details or clarity 。它目前不接受答案。












想改善这个问题吗?添加细节并通过 editing this post 澄清问题。

7年前关闭。



Improve this question




我正在努力学习 ruby 。
此时我有一个列表列表,我想要等效于以下 python 代码:
import itertools
l = [[1,2], [3], [10, 20, -4, 5]]
list(itertools.izip_longest(*l, fillvalue='NaN'))

结果是:
[(1, 3, 10), (2, 'NaN', 20), ('NaN', 'NaN', -4), ('NaN', 'NaN', 5)]

列表 l 中的列表数量可以不同。有没有一种简单的方法可以在 ruby​​ 中完成相同的操作?

最佳答案

我认为 Ruby 标准库中没有 izip_longest 的直接对应物。

l = [[99,2], [3], [10, 20, -4, 5]]
n = l.map{ |x| x.size }.max
(0...n).map { |i| l.map { |x| x.fetch(i, 'NaN') } }
# => [[99, 3, 10], [2, "NaN", 20], ["NaN", "NaN", -4], ["NaN", "NaN", 5]]

关于python - ruby 相当于 python izip_longest,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19579406/

10-11 07:57
查看更多