pythonプログラミングメモ
List 型の変数へのアクセス
list_neta = ["maguro","ika","ebi",'tako','suzuki','hirame','tai','ikura','uni',"aji"]
listのインデックスは「0」から始まることに注意。
list_neta[1:3]
['ika', 'ebi']
list_neta[:8] # 最初から8列目まで
['maguro', 'ika', 'ebi', 'tako', 'suzuki', 'hirame', 'tai', 'ikura']
list_neta[3:] # 4列目から最後まで
['ika', 'ebi', 'tako', 'suzuki', 'hirame', 'tai', 'ikura', 'uni', 'aji']
list_neta[::-1] # 最後の列から逆再生
['aji',
'uni',
'ikura',
'tai',
'hirame',
'suzuki',
'tako',
'ebi',
'ika',
'maguro']
list_neta[2:8][::-1] # 3列目から7列目まで抽出して逆再生
['ikura', 'tai', 'hirame', 'suzuki', 'tako', 'ebi']
appendとextendの違い
a = list(range(1,4))
a.append([1, 2])
[1, 2, 3, [1, 2]]
a.extend([1, 2])
[1, 2, 3, 1, 2]
制御構文
if文
# 基本形
a = 2
if a == 2:
print('a is 2')
elif a <= 0:
print('a is less than and equal to 0')
else:
print('a is something else')
a is 2
# 1行で書くことも可能
print('a is 2') if a == 2 else print('a is NOT 2')
a is 2
for文
# 基本形
colors = ['red', 'blue', 'green', 'yellow', 'white']
colors_png = []
for color in colors:
color_png = color + '.png'
colors_png.append(color_png)
colors_png
['red.png', 'blue.png', 'green.png', 'yellow.png', 'white.png']
# リスト内包表記(推奨)
[color + '.png' for color in colors]
['red.png', 'blue.png', 'green.png', 'yellow.png', 'white.png']
# enumerate
a = ["prius", "crown", "prius", "prius", "crown"]
b = [10, 20, 30, 40, 50]
c = 0
for idx, car in enumerate(a):
if car == "prius":
c += b[idx]
print(c)
80
lambda 関数
(lambda a,b:a*b)(3,5)
15