各言語のmap関数

beanz (2008年11月 2日 00:29) | コメント(1) | トラックバック(0)

リスト(配列等)の内容を元に別の内容に変換したリストが欲しい時map関数(メソッド)が使える。
まずは簡単なサンプルを

Perlでは

my @a = (1,2,3,4,5);
my @b = map ++$_, @a;

これで変数@bの内容は(2,3,4,5,6)になってる。

Rubyでは

a = [1,2,3,4,5]
b = a.map {|i| i + 1}

Pythonでは

a = [1,2,3,4,5]
b = map(lambda i: i + 1, a)

PHPでは

$a = array(1,2,3,4,5);
$b = array_map(create_function('$i', 'return ++$i;'), $a);

いずれも変数bは2から6までの整数のリストになっている。

次はもうちょっと複雑な例
あるディレクトリの中のすべてのファイルのファイル名とファイルサイズを格納したリスト(隠しファイルは除く)を出力したいとする。
構造的にはこんな感じ
[['ファイル名', 'ファイルサイズ'].....]

Perl:

#!/usr/bin/env perl
BEGIN {
    use File::Basename;
    chdir dirname $0;
}
use strict;
use warnings;
use IO::Dir;

my $dir = IO::Dir->new(".");
my @ fileAndSize = map [$_, -s $_], grep /^[^.]/, $dir->read();
print "$_->[0] => $_->[1]byte\n" for (@ fileAndSize);
$dir->close();

Ruby:

#!/usr/bin/env ruby
Dir.chdir File.dirname(ENV["_"])
Dir.open(".") do |dir|
    fileAndSize = dir.select {|i| i =~ /^[^.]/}.map {|i| [i, FileTest.size(i)]}
    fileAndSize.each {|l| puts "#{l[0]} => #{l[1]}byte"}
end

Python:

#!/usr/bin/env python
import os, re
os.chdir(os.path.dirname(os.environ['_']))
fileAndSize = map(lambda i: [i, int(os.path.getsize(i))], filter(lambda i: re.match('^[^.]', i), os.listdir(".")))
for i in fileAndSize: print "%s => %sbyte" % (i[0], i[1])

PHP:

#!/usr/bin/env php
<?php
chdir(dirname($_ENV[_]));
$files = glob("*");
$fileAndSize = array_map(create_function('$file', 'return array($file, filesize($file));'), $files);
foreach ($fileAndSize as $i) echo "$i[0] => $i[1]byte\n";
?>

言語によってはディレクトリをオープンしてたりglobを使ってたりするがすべて同じ出力になるはず。

カテゴリ:

トラックバック(0)

トラックバックURL: http://blog.beanz-net.jp/beanz_mtos/mt-tb.cgi/12

コメント(1)

In May, air jordan shoes launched an enhanced netbook, Latitude 2110 which features high definition display and built-in mobile broadband connectivity. There are a lot of evergreen trees, such as fir, spruce, hemlock, pine,air jordan shoes, and cedar. It does not cover the Indian, Pakistani, but also the retro jordan shoess of the present and past. A USB port can be located at the back of your computer near the serial port or parallel port. Furniture restoration, after all,jordan shoes, is a personal choice.
How could I have dela ffefedfdf##dfdf## yed my opportunity to reflect on my practice of school leadership? Lancaster City Football ClubLancaster - a historic British city famous for its castle, its battles, its Royal Grammar School and more recently populated by a large number of students at its university - has never been the site of great sporting achievement. At home, I抎 hoped I could get her out of the air jordan shoes seat without waking her, but that didn抰 happen. Examine what is hot in fashion custom suitcases to know which and how to pick low-cost replica designer luggage. Sophisticate Louis Vuitton craftmanship further strengthens your confidence.
Glee The 3D Concert Movie is actually a documentary on the live performance of the Glee cast during their summer 2011 tour. But hardy travelers might head to Alaska's city of Barrow. foodsafety japanesetreats resolvedThe name of the product says "hijiri", but google doesn't turn up anything food-related for that. Ronaldo is also an established national footballer for Brazil. Neighborhoods are buzzing with children sledding down jordan shoes covered hills,retro jordan shoes, and families are busily decorating their homes.
Initially,cheap jordan shoes, in the first week I started getting more painful pimples/zits but slowely all went away. Large, glitzy malls aren't the best places to look. There's even the same sculpting sculpting Cosmetic surgery The surgical reshaping of a tissue. This is a perfect gaming app for those who are headphone enthusiast. The supplements you find are overly prepared and weakened by processing.

相关的主题文章:









コメントする