「Python」の版間の差分

提供: Wikinote
移動: 案内検索
行39: 行39:
 
  a = a + [6, 7]  # 連結 → [0, 5, 6, 7]
 
  a = a + [6, 7]  # 連結 → [0, 5, 6, 7]
 
  a = a * 2      # 連続 → [0, 5, 6, 7, 0, 5, 6, 7]
 
  a = a * 2      # 連続 → [0, 5, 6, 7, 0, 5, 6, 7]
 +
 +
== その他 ==
 +
 +
=== getopt テンプレート ===
 +
どの言語でもこいつだけはテンプレート化する必要がある。。
 +
 +
ソースコード <toggledisplay>
 +
import sys, getopt
 +
def usage():
 +
    print "Usage: $s [-a] [-b str]" % sys.argv[0]
 +
    sys.exit(0)
 +
 +
try:
 +
    opts, args = getopt.getopt(sys.argv[1:], "ab:")
 +
except getopt.GetoptError:
 +
    usage()
 +
 +
(opt_a, opt_b) = (False, None) # defaults
 +
for (opt, val) in opts:
 +
    if opt == "-a":
 +
        opt_a = True
 +
    elif opt == "-b":
 +
        opt_b = val
 +
 +
for arg in args: # remainder
 +
    ...
 +
</toggledisplay>

2009年7月26日 (日) 15:29時点における版

だいぶ思い出してきた Python について。

参考リンク

文字列

  • シングルクォートとダブルクオートに違いはない。
    • エスケープシーケンスを無視する場合は raw 文字列を使う。r"raw 文字列\n"
  • 三重クォート """ あるいは ''' は改行をそのまま含めることができる。
  • 連結は + 演算子を用いる。
    • 文字列リテラルは、列記で連結可能。"ho" "ge" → "hoge"
  • len() 組み込み関数で長さを得る。
  • in で包含判定ができる

スライス

文字の間に添字を置くとわかりやすい。

s = "H e l l o"
    0 1 2 3 4 5
  - 5 4 3 2 1   ← ここは -0 でないことに注意!! (0 = -0 のため)

s[1]   → 'e'
s[:3]  → 'Hel' # 先頭 3 文字
s[3:]  → 'lo'
s[-4]  → 'e'
s[-3:] → 'llo' # 末尾 3 文字

リスト

書くのが面倒なくらい柔軟性に富んだデータ型である。

  • 変更可能 (mutable)
  • 入れ子可能 (リストの要素をリストにできる)
  • 文字列と同様のスライス表現で操作できる。
  • len() でリストの長さを得る。
a = []          # 初期化、クリア
a = [0, 3, 5]
a[1:1] = [1, 2] # 挿入 → [0, 1, 2, 3, 5]
a[1:4] = []     # 削除 → [0, 5]
a = a + [6, 7]  # 連結 → [0, 5, 6, 7]
a = a * 2       # 連続 → [0, 5, 6, 7, 0, 5, 6, 7]

その他

getopt テンプレート

どの言語でもこいつだけはテンプレート化する必要がある。。

ソースコード <toggledisplay>

import sys, getopt
def usage():
    print "Usage: $s [-a] [-b str]" % sys.argv[0]
    sys.exit(0)

try:
    opts, args = getopt.getopt(sys.argv[1:], "ab:")
except getopt.GetoptError:
    usage()

(opt_a, opt_b) = (False, None) # defaults
for (opt, val) in opts:
    if opt == "-a":
        opt_a = True
    elif opt == "-b":
        opt_b = val

for arg in args: # remainder
    ...

</toggledisplay>