同じ要素数の配列(リスト)を要素ごとにまとめて配列の配列を作るには (zip)
Scala 2013/09/17
Signature:
def scala.collection.Iterable[A]#zip(that: Iterable[B]): Iterable[(A, B)]
def scala.collection.Seq[A]#zip(that: Iterable[B]): Seq[(A, B)]
Python 2014/04/12
zip
関数を使う。
例
lst1 = [1, 2, 3]
lst2 = ["abc", "def", "ghi"]
zlst = zip(lst1, lst2)
print(zlst)
# Python2の場合
# [(1, 'abc'), (2, 'def'), (3, 'ghi')]
# Python3の場合
# <zip object at 0x7fb3dfbc43b0>
for e in zlst:
print(e)
# (1, 'abc')
# (2, 'def')
# (3, 'ghi')
長さが一致しないリストを与えると短い方に揃えられる。
Ruby / JRuby 2015/01/04
Array#zip
を使う。
p ['a', 'b'].zip([1, 2]) # => [["a", 1], ["b", 2]]
p ['a', 'b'].zip([1, 2], [3, 4]) # => [["a", 1, 3], ["b", 2, 4]]
Array#zip
| Ruby 2.1 リファレンスマニュアル
http://docs.ruby-lang.org/ja/2.1.0/method/Array/i/zip.html
Perl 2016/07/11
関数の自作例
sub zip {
my ($lst1, $lst2) = @_;
my @src1 = @$lst1;
my @src2 = @$lst2;
my @result = ();
while (@src1 && @src2) {
my $elem1 = shift(@src1);
my $elem2 = shift(@src2);
push(@result, [$elem1, $elem2]);
}
\@result;
}
my $lst1 = [1, 2, 3];
my $lst2 = [10, 20, 30];
my $zipped = zip($lst1, $lst2);
print Dumper $zipped;
# =>
# $VAR1 = [
# [
# 1,
# 10
# ],
# [
# 2,
# 20
# ],
# [
# 3,
# 30
# ]
# ];