对于多个数组
在Scheme中,您可以使用for-each
迭代多个列表:
> (for-each (lambda (a b) (display (+ a b)) (newline)) '(10 20 30) '(1 2 3))
11
22
33
>
我知道在Perl中您可以使用for
迭代单个列表。像方案示例中那样迭代多个列表的好方法是什么?
我对 Perl 5 或 6 的答案感兴趣。
In Scheme you can iterate over multiple lists in with for-each
:
> (for-each (lambda (a b) (display (+ a b)) (newline)) '(10 20 30) '(1 2 3))
11
22
33
>
I know that in Perl you can use for
to iterate over a single list. What's a good way to iterate over multiple lists as in the Scheme example?
I'm interested in answers for Perl 5 or 6.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
在 Perl 6 中,Zip 运算符是最好的选择。如果您想获取两个值(而不是直接计算总和),则可以使用不带加号的值:
In Perl 6, the Zip operator is the nicest choice. If you want to get both values (and not compute the sum directly), you can use it without the plus sign:
在 Perl 5 中,您可以使用模块 List::MoreUtils。可以使用成对的方式,也可以使用each_array 返回的迭代器(可以并行遍历两个以上的数组)。
In Perl 5 you can use the module List::MoreUtils. Either with pairwise or with the iterator returned by each_array (which can take more than two arrays to iterate through in parallel).
使用 Zip 运算符,您可以实现您使用 Scheme 所做的事情:
请参阅 http://perlcabal.org /syn/S03.html#Zip_operators
With the Zip operator you can achieve what you're doing with Scheme:
See http://perlcabal.org/syn/S03.html#Zip_operators
如果您确定数组的索引大小相同,则可以迭代它们:
You could just iterate over the indices of the arrays, if you're sure they're the same size:
Algorithm::Loops 提供了一个 MapCar 函数,用于迭代多个数组(具有以不同方式处理不平等问题的变体)大小的数组)。
Algorithm::Loops offers a MapCar function for iterating over multiple arrays (with variants that deal differently with unequally sized arrays).
一种方法是:
使用
List::MoreUtils
中的each_arrayref
:感谢 Alex 指出
List::MoreUtils
。One way is:
Using
each_arrayref
fromList::MoreUtils
:Thanks to Alex for pointing out
List::MoreUtils
.只要问题很简单,只需添加(/乘法、除法……)即可
数组不是数组的数组,您还可以使用超级运算符来完成您的任务:(
当然这是 Perl6 答案)
如果您无法访问法语引号
«»
,您可以将其重写为As long as the question is as simple as just adding (/multiplying, dividing,…) and the
Arrays are no Arrays of Arrays, you also could use the hyper-operators for your task:
(of course this is a Perl6 answer)
if you don't have access to the French quotes
«»
, you could rewrite it as一种解决方案(有很多可供选择)可能如下所示:
我感觉您正在询问
foreach
,它可能如下所示:但在这种情况下它并不那么顺利。如果任一数组较短会发生什么?
One solution (there are many to choose from) might look like this:
I sense that you are asking about
foreach
, which might look like this:But it is not as smooth in this case. What happens if either array is shorter?