javascript中是否有类似于Python的zip函数?也就是说,给定多个相等长度的数组,创建一个由对组成的数组。
例如,如果我有三个这样的数组:
var array1 = [1, 2, 3];
var array2 = ['a','b','c'];
var array3 = [4, 5, 6];
输出数组应该是:
var outputArray = [[1,'a',4], [2,'b',5], [3,'c',6]]
javascript中是否有类似于Python的zip函数?也就是说,给定多个相等长度的数组,创建一个由对组成的数组。
例如,如果我有三个这样的数组:
var array1 = [1, 2, 3];
var array2 = ['a','b','c'];
var array3 = [4, 5, 6];
输出数组应该是:
var outputArray = [[1,'a',4], [2,'b',5], [3,'c',6]]
当前回答
Mochikit库提供了这个函数和许多其他类似python的函数。Mochikit的开发者也是一个Python爱好者,所以它具有Python的一般风格,并且还将异步调用包装在一个扭曲的框架中。
其他回答
和@Brandon一样,我推荐Underscore的zip功能。但是,它的作用类似zip_longest,根据需要附加未定义的值以返回最长输入的长度。
我使用mixin方法用zipshort扩展下划线,它的作用类似于Python的zip,基于库自己的zip源代码。
你可以在你的普通JS代码中添加以下代码,然后像调用下划线一样调用它:_。zipShortest ([1, 2, 3], [a])返回[[1,' ']],例如。
// Underscore library addition - zip like python does, dominated by the shortest list
// The default injects undefineds to match the length of the longest list.
_.mixin({
zipShortest : function() {
var args = Array.Prototype.slice.call(arguments);
var length = _.min(_.pluck(args, 'length')); // changed max to min
var results = new Array(length);
for (var i = 0; i < length; i++) {
results[i] = _.pluck(args, "" + i);
}
return results;
}});
python zip函数的生成器方法。
function* zip(...arrs){
for(let i = 0; i < arrs[0].length; i++){
a = arrs.map(e=>e[i])
if(a.indexOf(undefined) == -1 ){yield a }else{return undefined;}
}
}
// use as multiple iterators
for( let [a,b,c] of zip([1, 2, 3, 4], ['a', 'b', 'c', 'd'], ['hi', 'hello', 'howdy', 'how are you']) )
console.log(a,b,c)
// creating new array with the combined arrays
let outputArr = []
for( let arr of zip([1, 2, 3, 4], ['a', 'b', 'c', 'd'], ['hi', 'hello', 'howdy', 'how are you']) )
outputArr.push(arr)
没有等价的函数。如果你只有几个数组,你应该使用for循环获取一个索引,然后使用索引访问数组:
var array1 = [1, 2, 3];
var array2 = ['a','b','c'];
for (let i = 0; i < Math.min(array1.length, array2.length); i++) {
doStuff(array1[i], array2[i]);
}
如果你有更多的数组,你可以在数组上有一个内循环。
惰性生成器解决方案的一个变体:
function* iter(it) { yield* it; } function* zip(...its) { its = its.map(iter); while (true) { let rs = its.map(it => it.next()); if (rs.some(r => r.done)) return; yield rs.map(r => r.value); } } for (let r of zip([1,2,3], [4,5,6,7], [8,9,0,11,22])) console.log(r.join()) // the only change for "longest" is some -> every function* zipLongest(...its) { its = its.map(iter); while (true) { let rs = its.map(it => it.next()); if (rs.every(r => r.done)) return; yield rs.map(r => r.value); } } for (let r of zipLongest([1,2,3], [4,5,6,7], [8,9,0,11,22])) console.log(r.join())
这是python经典的“n-group”习语zip(*[iter(a)]*n):
triples = [...zip(...Array(3).fill(iter(a)))]
Python有两个压缩序列的函数:zip和itertools.zip_longest。Javascript中相同功能的实现如下所示:
Python的zip在JS/ES6上的实现
const zip = (...arrays) => {
const length = Math.min(...arrays.map(arr => arr.length));
return Array.from({ length }, (value, index) => arrays.map((array => array[index])));
};
结果:
console.log(zip(
[1, 2, 3, 'a'],
[667, false, -378, '337'],
[111],
[11, 221]
));
[[1, 667, 111, 11]
console.log(zip(
[1, 2, 3, 'a'],
[667, false, -378, '337'],
[111, 212, 323, 433, '1111']
));
[[1、667、111],[2,假的,212年],[3、-378、323],[' a ', “337”,433]]
console.log(zip(
[1, 2, 3, 'a'],
[667, false, -378, '337'],
[111],
[]
));
[]
Python的zip_longest在JS/ES6上的实现
(https://docs.python.org/3.5/library/itertools.html?highlight=zip_longest # itertools.zip_longest)
const zipLongest = (placeholder = undefined, ...arrays) => {
const length = Math.max(...arrays.map(arr => arr.length));
return Array.from(
{ length }, (value, index) => arrays.map(
array => array.length - 1 >= index ? array[index] : placeholder
)
);
};
结果:
console.log(zipLongest(
undefined,
[1, 2, 3, 'a'],
[667, false, -378, '337'],
[111],
[]
));
[[1,667, 111, undefined], [2, false, undefined, undefined], [3, -378, undefined, undefined], ['a', '337', undefined, 未定义
console.log(zipLongest(
null,
[1, 2, 3, 'a'],
[667, false, -378, '337'],
[111],
[]
));
[[1, 667, 111, null], [2, false, null, null], [3, -378, Null, Null], ['a', '337', Null, Null]]
console.log(zipLongest(
'Is None',
[1, 2, 3, 'a'],
[667, false, -378, '337'],
[111],
[]
));
[[1,667, 111, 'Is None'], [2, false, 'Is None', 'Is None'], [3, -378,“没有”,“没有 ' ], [ ' ”、“337”、“没有”、“ 没有']]