用另一个数组的元素替换数组中的所有零 [英] Replace all zeros in array with elements of another array

查看:354
本文介绍了用另一个数组的元素替换数组中的所有零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个像这样的数组:

Say I've got an array like this:

array_1 =  [0, 0, 1, 2, 3, 0]

和另一个类似的东西:

array_2 = [4, 5, 6]

如何我可以创建一个像这样的数组,以便 array_1 中的每个0替换为 array_2 ?:

How can I create an array like this, such that each 0 in the array_1 is replaced by the first and subsequent elements of the array_2?:

[4,5,1,2,3,6]

也就是说,每次在第一个数组中遇到 0 时,我们都希望将其替换为 array_2.shift

That is, every time we encounter a 0 in the first array, we'd like to replace it with the result of array_2.shift.

推荐答案

这个较短,但 shift 方法将就地修改array_2。

This one is shorter but the shift method it will modify array_2 in-place.

array_1.map {|x| x == 0 ? array_2.shift : x}

以下代码使用带有外部迭代的枚举器对象,不会修改任何

The following uses an enumerator object with external iteration and will not modify any of the original arrays.

e = array_2.each
array_1.map {|x| x == 0 ? e.next : x}

这篇关于用另一个数组的元素替换数组中的所有零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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