2016-03-25   python 

Python写経(ループと条件)

辞書のループ

dict = { 'key1': 123, 'key2': 456, 'key3': 789 }
for key, value in dict.items():
    print(key, value)
key1 123
key2 456
key3 789

シーケンスのループ

list = [ 123, 456, 789 ]
for index, value in enumerate(list):
    print(index, value)
0 123
1 456
2 789

zipを使ったループ

seq1 = [ 'aaa', 'bbb', 'ccc' ]
seq2 = [ 'xxx', 'yyy', 'zzz' ]

for t in zip(seq1, seq2):
    print(t)

for a, x in zip(seq1, seq2):
    print(a, x)
('aaa', 'xxx')
('bbb', 'yyy')
('ccc', 'zzz')
aaa xxx
bbb yyy
ccc zzz

rangeを使ったループ

start = 0
end = 10
step = 2
for k in range(start, end, step):
    print(k)
0
2
4
6
8

reversedを使ったループ

seq = range(0, 5)

for k in seq:
    print(k)

print()

for k in reversed(seq):
    print(k)
0
1
2
3
4

4
3
2
1
0

sortedでソート、setは重複している要素をユニークに

seq = [ 3, 1, 4, 1, 5 ]

for k in seq:
    print(k)

print()

for k in sorted(seq):
    print(k)

print()

for k in sorted(set(seq)):
    print(k)
3
1
4
1
5

1
1
3
4
5

1
3
4
5

in演算子

seq = [ 3, 1, 4, 1, 5 ]

if 4 in seq:
    print('Exist')
else:
    print('Not exist')

# => Exist

比較演算子の連結

seq = [3, 1, 4, 1, 5, 9]

for k in seq:
    if 1 < k < 5:
        print(k)
3
4

andはショートカット演算子

seq = [ 0, 1, 2, 3 ]

for n in range(0,1000):
    if 0 <= n < len(seq) and seq[n] > 0:
        print(n)
1
2
3

真偽値

seq = [ '', 0, True, False, 'Hello' ]

for x in seq:
    if x:
        print(x)
True
Hello

参照

http://docs.python.jp/3/tutorial/datastructures.html#looping-techniques

 2016-03-25   python