メインコンテンツまでスキップ

「Loop」タグの記事が8件件あります

全てのタグを見る

Shell Script: for文 - ワードリストに変数、コマンドを使用

· 約1分
Yu Sasaki
Enterprise Security Manager / Advisor

以下のシェルスクリプトはfor文のワードリストに文字列変数を使用したもの。文字列はスペース区切でパラメータ変数に格納されloopする。また、ワードリストにバッククォートで括ったコマンドを指定すると、そのコマンドの実行結果がパラメータ変数に渡される。

#!/bin/sh
VARS="1 2 3 four five"
for VAR in $VARS
do
echo $VAR
done
echo ""
for LIST in `date`
do
echo $LIST
done

Python: 正規表現の基本 - 最長、最短マッチング

· 約3分
Yu Sasaki
Enterprise Security Manager / Advisor

直前の文字、メタ文字を繰り返しマッチングさせる量指定記号である「*」「+」「?」などは、テキスト中にその繰り返しパターンがマッチする箇所が複数ある場合は、通常最後にマッチした箇所をオブジェクトに記録します。このような最長マッチングに対して、マッチング箇所が複数の場合に最初にマッチした箇所を記録する最短マッチング方法があります。 最短マッチングを行う量指定記号は最長マッチングの記号の末尾に「?」を付けるだけです。すなわち、最長の量指定が「*」「+」「?」であるのに対して、**最短マッチングは「*?」「+?」「??」**となります。それでは、以下のコードで確認してみましょう。

ソースコード

# coding: Shift_JIS import re # 正規表現を扱うモジュールのインポート # 正規表現のチェックプリント用の関数 def PrintRegMatch(pat, txt): # 書式: re.search(パターン, テキスト) m = re.search(pat, txt) # パターンにマッチしなかった場合はNoneを返す if m != None: print 'パターン: "%s"nテキスト: "%s"nマッチ : する' % (pat, txt) print 'マッチング開始位置:', m.start() print 'マッチング終了位置:', m.end() else: print 'パターン: "%s"nテキスト: "%s"nマッチ: しない' % (pat, txt) print return m # サンプルテキスト txt = '

Hello! World!!

Goodbye World

' # 最長: .* # 最短: .*? PrintRegMatch('

.*

', txt) # 最長: 文字列末尾の

にマッチ PrintRegMatch('

.*?

', txt) # 最短: World!!



にマッチ # 最長: .+ # 最短: .+? PrintRegMatch('

.+

', txt) # +?は直前の文字の1文字以上の繰り返し PrintRegMatch('

.+?

', txt) # ↑の控えめマッチング # 最長: .? # 最短: .?? PrintRegMatch('B.?C', 'BCCC') # ?は直前の文字の0 or 1回の繰り返し PrintRegMatch('B.??C', 'BCCC') # ??はその控えめ(ry

re.searchはre.matchと異なり、パターンをテキスト文字列の先頭以外にもマッチさせます。

実行結果

パターン: "

.*

" テキスト: "

Hello! World!!

Goodbye World

" マッチ : する マッチング開始位置: 0 マッチング終了位置: 41 パターン: "

.*?

" テキスト: "

Hello! World!!

Goodbye World

" マッチ : する マッチング開始位置: 0 マッチング終了位置: 21 パターン: "

.+

" テキスト: "

Hello! World!!

Goodbye World

" マッチ : する マッチング開始位置: 0 マッチング終了位置: 41 パターン: "

.+?

" テキスト: "

Hello! World!!

Goodbye World

" マッチ : する マッチング開始位置: 0 マッチング終了位置: 21 パターン: "B.?C" テキスト: "BCCC" マッチ : する マッチング開始位置: 0 マッチング終了位置: 3 パターン: "B.??C" テキスト: "BCCC" マッチ : する マッチング開始位置: 0 マッチング終了位置: 2

リファレンス

Python: リスト中の文字列を大文字⇔小文字に変換

· 約2分
Yu Sasaki
Enterprise Security Manager / Advisor

文字列を比較する際に、大文字・小文字を区別したくない場合があります。その時は、比較する文字列を大/小文字列のどちらかに統一しておく、という手があります。Pythonでは大文字・小文字変換メソッドlower()、upper()はstringオブジェクトに組み込まれています。 今回は、その使い方と実際に使用する状況に近いデータ構造、ここでは変換対象文字列がリスト中の要素である場合を想定し、for文とリストコンプリヘンション(リスト内包表記)の両表記を以下に示します。

ソースコード

#!/usr/bin/python
# coding: UTF-8
# リスト中の文字列要素を大文字⇔小文字変換
str_atog = "ABCDEFG"
str_hton = "hijklmn"
# lower(), upper()メソッドの使い方
print "大文字(列) %s を小文字(列) %s に変換" % (str_atog, str_atog.lower())
print "小文字(列) %s を大文字(列) %s に変換" % (str_hton, str_hton.upper())
print
arr = ['And', 'Begin', 'Code', 'Double']
arr2 = ['end', 'flag', 'gem', 'halt']
# for文で小文字[大文字](列)を要素とするリストを生成
n_arr = []
for str in arr:
n_arr.append(str.lower())
print n_arr
n_arr2 = []
for str in arr2:
n_arr2.append(str.upper())
print n_arr2, 'n'
# リストコンプリヘンションで小文字[大文字](列)を要素とするリストを生成
print [str.lower() for str in arr]
print [str.upper() for str in arr2]

実行結果

大文字(列) ABCDEFG を小文字(列) abcdefg に変換
小文字(列) hijklmn を大文字(列) HIJKLMN に変換
['and', 'begin', 'code', 'double']
['END', 'FLAG', 'GEM', 'HALT']
['and', 'begin', 'code', 'double']
['END', 'FLAG', 'GEM', 'HALT']

List Comprehensions ならワンライナーで書けるってのは地味に良いですね。 話変わりますが、Rubyにもイテレータやブロックを用いた簡略記法がありましたね。アレはアレで、応用しやすいものです。

チュートリアル

リファレンス

Python: if/for文でのin演算子の各オブジェクト毎の評価

· 約3分
Yu Sasaki
Enterprise Security Manager / Advisor

if/for文中で使われるin演算子の評価はオブジェクトごとに微妙に変化します。あやふやなままにしておくのもなんですし、ここで、以下のオブジェクトに対するif/for文中の評価を実際に確認してみましょう。

  • 文字列
  • リスト
    • 数値のリスト
    • 文字列のリスト
    • 辞書のリスト
  • 辞書

if/for文 + in 文字列

#!/usr/bin/python
# coding: UTF-8
str1 = "abcdefghijklmn" # 文字列
# if 「検索する文字列」 in 「検索される文字列」:
elem = 'def'
if elem in str1:
print '文字列 "%s" に "%s" は存在する。' % (str1, elem)
print
# for 「要素(文字)」 in 「文字列」:
for ch in str1:
print ch, # str1の先頭の文字から順に繰り返す

実行結果

文字列 "abcdefghijklmn" に "def" は存在する。
a b c d e f g h i j k l m n

if/for文 + in リスト

#!/usr/bin/python
# coding: UTF-8
nums = [1, 2, 3, 4, 5] # 数値のリスト
chs = ['a', 'b', 'c', 'd'] # 文字列のリスト
dics = [{'one':1}, {'two':2}, {'three':3}, {'four':4}] # 辞書のリスト
# if 「検索する要素」 in 「検索されるリスト」:
elem = 3
if elem in nums:
print 'リスト %s に要素の %d は存在する。' % (nums, elem)
elem = 'b'
if elem in chs:
print 'リスト2 %s に要素の %s は存在する。' % (chs, elem)
elem = {'two':2}
if elem in dics:
print 'リスト3 %s に要素の %s は存在する。' % (dics, elem)
print
# for 「リストの要素」 in 「リスト」:
for e_num in nums:
print e_num,
print
for e_ch in chs:
print e_ch,
print
for e_dic in dics:
print e_dic,

実行結果

リスト [1, 2, 3, 4, 5] に要素の 3 は存在する。
リスト2 ['a', 'b', 'c', 'd'] に要素の b は存在する。
リスト3 [{'one': 1}, {'two': 2}, {'three': 3}, {'four': 4}] に要素の {'two': 2} は存在する。
1 2 3 4 5
a b c d
{'one': 1} {'two': 2} {'three': 3} {'four': 4}

if/for文 + in 辞書

#!/usr/bin/python
# coding: UTF-8
dic = {'one':1, 'two':2, 'three':3, 'four':4} # 辞書
# if 「検索するキー」 in 「検索される辞書」:
elem = 'three'
if elem in dic: # 辞書のキーの検索
print '辞書 %s に要素の「キー」 %s は存在する。' % (dics, elem)
print
# for 「辞書のキー」 in 「辞書」:
for key in dic: # for key in dic.keys(): と同じ
print key,
print
for v in dic.values(): # 値を要素として繰り返す
print v,
print
for (k, v) in dic.items(): # (キー, 値)のタプルを要素として繰り返す
print "%s:%s, " % (k, v),

実行結果

辞書 [{'one': 1}, {'two': 2}, {'three': 3}, {'four': 4}] に要素の「キー」 three は存在する。
four three two one
4 3 2 1
four:4, three:3, two:2, one:1,

チュートリアル

リファレンス

Python: 正規表現の基本 - 繰り返し「*」「+」「?」

· 約2分
Yu Sasaki
Enterprise Security Manager / Advisor

ソースコード

# coding: Shift_JIS
import re # 正規表現を扱うモジュールのインポート
# 正規表現のチェックプリント用の関数
def PrintRegMatch(pat, txt):
# 書式: re.match(パターン, テキスト)
m = re.match(pat, txt) # パターンにマッチしなかった場合はNoneを返す
if m != None: print 'パターン"%s"はテキスト"%s"にマッチ「する」' % (pat, txt)
else: print 'パターン"%s"はテキスト"%s"にマッチ「しない」' % (pat, txt)
txt = 'ABCDEFGH' # 探索される文字列をテキスト
# 探索する 文字列をパターン
# 「*」: 直前の文字の0回以上の繰り返しにマッチ
PrintRegMatch('.*CDE', txt)
PrintRegMatch('A.*H', txt)
PrintRegMatch('A*BC', txt)
PrintRegMatch('A.*BC', txt)
PrintRegMatch('A*', '')
print
# 「+」: 直前の文字の1回以上の繰り返しにマッチ
PrintRegMatch('.+DEF', txt)
PrintRegMatch('A.+H', txt)
PrintRegMatch('A+BC', txt)
PrintRegMatch('A.+BC', txt)
PrintRegMatch('A+', '')
print
# 「?」: 直前の文字の0or1回の繰り返しにマッチ
PrintRegMatch('^A?.+$', txt)
PrintRegMatch('^B?$', '')
PrintRegMatch('^C?E', 'E')
PrintRegMatch('A.?H', txt)
PrintRegMatch('BBB?C', 'BBC')

実行結果

パターン".*CDE"はテキスト"ABCDEFGH"にマッチ「する」
パターン"A.*H"はテキスト"ABCDEFGH"にマッチ「する」
パターン"A*BC"はテキスト"ABCDEFGH"にマッチ「する」
パターン"A.*BC"はテキスト"ABCDEFGH"にマッチ「する」
パターン"A*"はテキスト""にマッチ「する」
パターン".+DEF"はテキスト"ABCDEFGH"にマッチ「する」
パターン"A.+H"はテキスト"ABCDEFGH"にマッチ「する」
パターン"A+BC"はテキスト"ABCDEFGH"にマッチ「する」
パターン"A.+BC"はテキスト"ABCDEFGH"にマッチ「しない」
パターン"A+"はテキスト""にマッチ「しない」
パターン"^A?.+$"はテキスト"ABCDEFGH"にマッチ「する」
パターン"^B?$"はテキスト""にマッチ「する」
パターン"^C?E"はテキスト"E"にマッチ「する」
パターン"A.?H"はテキスト"ABCDEFGH"にマッチ「しない」
パターン"BBB?C"はテキスト"BBC"にマッチ「する」

リファレンス

Python: リスト内包表記(リストコンプリヘンション)をfor文に書き換える

· 約3分
Yu Sasaki
Enterprise Security Manager / Advisor

リスト内包表記を知ることでコードのリーディングとライティングを早めることが出来ます(パフォーマンスもfor文より良いです)。そこでリスト内包表記とfor文の書き換え方を以下に紹介。

ソースコード

#!/usr/bin/python
# coding: UTF-8
# リスト内包表記(リストコンプリヘンション)をfor文に書き換える
# List Comprehensions
print [a for a in range(10)]
# 0~9の数値を要素とするリスト
a2 = []
for i in range(10):
a2.append(i)
print a2
print [b*2 for b in range(10)] # ループのパラメータに演算を行う
# 0~9の数値の×2の結果を要素とするリスト
b2 = []
for i in range(10):
b2.append(i*2)
print b2
print [c for c in range(10) if c % 2 == 1] # 条件を指定してリストを生成
# in の被演算子を評価後、取り出された要素cをif文にかける。if文が偽のときは、とばして次のループに入る
# 結果として、0~9の数値の中で条件「c % 2 == 1」を満たす、すなわち奇数を要素とするリスト
c2 = []
for i in range(10):
if (i % 2 == 1):
c2.append(i)
print c2
print '\n', b2
print [d+1 for d in b2]
d2 = []
for i in b2:
d2.append(i+1)
print d2
e = 'It is important to set my aims but at the same time I should confirm my present condition.'
print '\n', e
print [wd for wd in e.split(' ')]
e2 = []
for i in e.split(' '):
e2.append(i)
print e2

実行結果

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[1, 3, 5, 7, 9]
[1, 3, 5, 7, 9]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
It is important to set my aims but at the same time I should confirm my present condition.
['It', 'is', 'important', 'to', 'set', 'my', 'aims', 'but', 'at', 'the', 'same', 'time', 'I', 'should', 'confirm', 'my', 'present', 'condition.']
['It', 'is', 'important', 'to', 'set', 'my', 'aims', 'but', 'at', 'the', 'same', 'time', 'I', 'should', 'confirm', 'my', 'present', 'condition.']

一般化

[新しいリストに格納する要素(*1) for OLD_ELEMENT in OLD_LIST if 条件式] *1: 式を書く

追記(2008-6-17): 文字列の1文字ごとの処理

>>> str = 'hello! hello!'
>>> ' '.join([c.upper() for c in str])
'H E L L O ! H E L L O !'
>>>

ここでの処理内容は、upper()メソッドによる英小文字→大文字の変換です。

チュートリアル

Python: 辞書の全てのキーと値をたどる - items(), keys(), values()メソッド

· 約2分
Yu Sasaki
Enterprise Security Manager / Advisor

ソースコード

#!/usr/bin/python
# coding: UTF-8
# 辞書の全てのキーと値をたどる | items(), keys(), values()メソッドの使い方
# 辞書の初期化
profile = { 'Hana':19, 'Toru':26, 'Katori':15, 'Sato':45}
print profile, '\n' # 出力して確認
# 辞書のitems()メソッドで全てのキー(key), 値(value)をたどる
for k, v in profile.items(): # for/if文では文末のコロン「:」を忘れないように
print k, v
# items()メソッドの戻り値
print 'items():', profile.items(), '\n' # keyとvalueのタプルのリストを返している
# 辞書のkeys()メソッドで全てのキーをたどる
for k in profile.keys():
print 'key:', k
# keys()メソッドの戻り値
print 'keys():', profile.keys(), '\n' # keyリストを返している
# 辞書のvalues()メソッドで全ての値をたどる
for v in profile.values():
print 'value:', v
# values()メソッドの戻り値
print 'values():', profile.values(), '\n' # valueのリストを返している

実行結果

{'Toru': 26, 'Hana': 19, 'Katori': 15, 'Sato': 45}
Toru 26
Hana 19
Katori 15
Sato 45
items(): [('Toru', 26), ('Hana', 19), ('Katori', 15), ('Sato', 45)]
key: Toru
key: Hana
key: Katori
key: Sato
keys(): ['Toru', 'Hana', 'Katori', 'Sato']
value: 26
value: 19
value: 15
value: 45
values(): [26, 19, 15, 45]

リファレンス

チュートリアル