- リストの繰り返し
[0] * 10
['a', 'b', 'c'] * 3
- リスト内で、特定の値に等しい要素番号の最小値
l = ['A', 'B', 'B', 'C']
l.index('B')
- 固定数ごとに抜き出す(サブスクリプティング)
x = ["A", "B", "C", "D", "E", "F"]
x[1::3]
x[0::2]
- 辞書(dictionary)のkeyの一覧
d = { "name":"tarou" , "address":"tokyo", "age":30, "hobby":["igo", "chess", "shogi"] }
d.keys()
- 辞書を拡張する
d = { "name":"tarou" , "address":"tokyo" }
d.update( {"age":30, "hobby":["igo", "chess", "shogi"]} )
- 集合演算
set(range(5)) & set(range(3))
set(['a', 'b']) | set(['a', 'c', 'd'])
set(range(4)) - set([2])
- リスト内の重複を取り除く: 一度集合にしてからリストに戻せばいい。ただし順番は狂う。
x = ['a', 'b', 'c', 'b', 'c']
list(set(x))
- リストをCSVに保存。csv.writerを利用。
x = [ ["x", "y", "z"], [10, 5, 3], [1, "XYZ", 3], ["5", 1, "ABC"] ]
with open('test.csv', 'wb') as f:
ff = csv.writer(f)
for row in x:
ff.writerow(row)
- 辞書をCSVに保存。csv.DictWriterを利用。データは辞書のリスト。
data = [ {"name":"ichiro", "age":20} , {"name":"tarou", "age":15} ,{"name":"takuro", "age":30} ]
head = ("name", "age")
with open("test.csv", "wb") as f:
ff = csv.DictWriter(f, head)
for row in data:
ff.writerow(row)
- DictWriter使用時に、ヘッダー行を入れるためのテクニック
data = [ {"name":"ichiro", "age":20} , {"name":"tarou", "age":15} ,{"name":"takuro", "age":30} ]
head = ("name", "age")
with open("test.csv", "wb") as f:
ff = csv.DictWriter(f, head)
# ここ
row = dict( (n, n) for n in head )
ff.writerow(row)
for row in data:
ff.writerow(row)