LoginSignup
0
0

More than 1 year has passed since last update.

PerlとPythonでありがちな配列検索処理の書き方

Posted at

久々に忘れたのでメモ

完全一致

image.png

Perl

grep1.pl
use strict;
use warnings;
my $text = "AAA";
my @lst1 = ( "AAA",  "BBB", "CCC" );
# 完全一致
if ( grep $text eq $_, @lst1 ) {
        print("match1\n"); # match1が出力
}

Python

grep1.py
text = "AAA"
lst1 = ["AAA", "BBB", "CCC"]
# 完全一致
if text in lst1:
    print("match1") # match1が出力

部分一致

image.png

Perl

grep2.pl
use strict;
use warnings;
my $text = "AAA";
my @lst2 = ( "AAAA", "BBB", "CCC" );
# 部分一致
if ( grep /$text/, @lst2 ) {
        print("match2\n"); # match2が出力
}

Python

grep2.py
text = "AAA"
lst2 = ["AAAA", "BBB", "CCC"]
# 部分一致
if [True for _ in lst2 if text in _]:
    print("match2") # match2が出力

逆部分一致

image.png

Perl

grep3.pl
use strict;
use warnings;

my $text = "AAA";
my @lst3 = ( "A",    "B",   "C", "D" );
# 逆部分一致
if ( grep $text =~ /$_/, @lst3 ) {
        print("match3\n"); # match3が出力
}

Python

grep3.py
text = "AAA"
lst3 = ["A", "B", "C"]
# 逆部分一致
if [True for _ in lst3 if _ in text]:
    print("match3") # match3が出力
0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0