将行数组转换为列数组
将任何(等长)行数组转换为列数组的最优雅的方法是什么?
例如:
[1,2,3]
[4,5,6]
# To
[1,4]
[2,5]
[3,6]
这就是我到目前为止所拥有的:
grid = [
[1,2,3]
[4,5,6]
]
grid2 = []
for i in grid[0]
grid2.push []
for row, y in grid
for el, x in row
grid2[x].push el
是否有 1-liner 可以做到这一点?
What would be the most elegant way to turn any array of (equal length) rows into an array of columns?
Eg:
[1,2,3]
[4,5,6]
# To
[1,4]
[2,5]
[3,6]
This is what I have so far:
grid = [
[1,2,3]
[4,5,6]
]
grid2 = []
for i in grid[0]
grid2.push []
for row, y in grid
for el, x in row
grid2[x].push el
Is there maybe even a 1-liner that would do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Javascript 中,如果您在使用 ECMAScript 5 数组方法的环境中工作,则
map()
函数可以很好地实现这一点:如果您取消了换行符,这可能是单行代码。 :)
CoffeeScript:
In Javascript, if you are working in an environment with ECMAScript 5 array methods, the
map()
function works nicely for this:This could be a one-liner if you killed the line breaks. :)
CoffeeScript:
不要将 for..in 与顺序很重要的数组一起使用!
将 for..in 与数组一起使用具有以下危险:
所有都会返回数组的可枚举属性,包括 Array.prototype 上的属性和数组本身,因此您必须绝对确信没有发生此类扩展,或者您必须执行 hasOwnProperty 和数字索引检查
返回键的顺序无法保证,并且很容易受到干扰 - IE 按照添加顺序返回它们,因此如果它们添加顺序不正确(例如使用递减 while 循环,这很常见)他们将以相反的顺序返回
在 Firefox 和 IE 中尝试以下操作:
在顺序很重要的情况下,仅使用按所需顺序显式访问密钥的循环。这也适用于对象,因为在 javascript 中,使用 for..in 为 all 对象返回属性的顺序是依赖于实现的,并且随浏览器的不同而变化(请注意,在 javascript 中,一切都是对象)。
For..in 可以与上述问题不重要或已得到处理的数组一起使用。它是用于稀疏数组和访问非数字可枚举属性的便捷工具。
通用的转置函数是:
它可以被缩短和优化,但上面是一个性能合理且易于维护的函数。
Don't use for..in with arrays where order is important!!
Using for..in with arrays has the following dangers:
All enumerable properties of the array will be returned, including those on Array.prototype and the array itself so either you must be absolutely confident that no such extensions have occurred, or you must do hasOwnProperty and numeric index checks
The order in which keys are returned is not guaranteed and can easily be disturbed - IE returns them in the order they are added, so if they are added out of order (e.g. using a decrementing while loop, which is quite common) they will returned in reverse order
Try the following in Firefox and IE:
Where order is important, only use loops where you explicitly access keys in the order you require. This also applies to objects, since in javascript the order in which properties are returned using for..in for all objects is implementation dependent and varies across browsers (noting that in javascript, everything is an object).
For..in is OK to use with arrays where the above issues are either not important or are dealt with. It is a handy tool for sparse arrays and accessing non-numeric enumerable properties.
A generic transpose function is:
It can be shortened and optimisied, but the above is a reasonably performant and easily maintained function.
试试这个:
会给你一个结果:
Try this:
Would get you a result of:
咖啡脚本:
CoffeeScript: