目次
プログラミング教育者。ScratchやPythonを教えています。
工作HardwareHubからのお知らせ
whileループ
sample.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
x = 10
while x:
print x, # カンマをつけると改行せずに空白区切りで出力
x -= 1 # pythonにはデクリメント演算子が存在しない (インクリメント演算子もない)
else: print x # while判定が偽の後に実行される (break後は実行されない)
while False: print 'while' # 参考: do while, until はPythonにはない
else: print 'else' # break, continue が使用可能
while 1: pass # pass: 何もしない行であることを明示
# while x=1: pass # これはエラー (pythonでは代入ステートメントを式として使用できない)
出力例
$ python sample.py
10 9 8 7 6 5 4 3 2 1 0
else
(Ctrl-c KeyboardInterrupt)
forループ
sample.py
for x in ['a', 'b', 'c']:
print x,
else: print 'd' # whileと同様にfor判定が偽となると実行される (break後は実行されない)
for x in (1, 2, 3): print x**2,
for x in "DEF": print x,
for (x,y) in [(1,2), (3,4), (5,6)]: print x,y
res = [[],[]]
for x in ("alpha", "beta", "gamma"): res[0].append(x*2)
for x in ("alpha", "beta", "gamma"): res[1].extend([x,x*2]) # 複数要素の追加時 (厳密にはリストの追加時) はextendを用いる
print res
出力例
$ python sample.py
a b c d
1 4 9 D E F 1 2
3 4
5 6
[['alphaalpha', 'betabeta', 'gammagamma'], ['alpha', 'alphaalpha', 'beta', 'betabeta', 'gamma', 'gammagamma']]
リスト内包表記 (for)
sample.py
print [2**x for x in [0,1,2,3,4,5,6,7,8,9,10]]
print [2**x for x in [0,1,2,3,4,5,6,7,8,9,10] if x%2==0]
List = ['a','b','c']
print [x+y for x in List for y in List]
出力例
$ python sample.py
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
[1, 4, 16, 64, 256, 1024]
['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']
イテレータ
sample.py
List = ['a','b','c']
Iter = iter(List)
print Iter.next()
print Iter.next()
print Iter.next()
出力例
$ python sample.py
a
b
c
ディクショナリ
#!/usr/bin/python
# -*- coding: utf-8 -*-
Dict = {'key1':'val1',
'key2':'val2',
'key3':'val3'}
Iter = Dict.iteritems()
for key, value in Iter:
print key
print value
ジェネレータ
イテレータの一種であるジェネレータは以下のように作成します。Scala のストリームのように遅延評価されるため、巨大な配列を利用したい場合等であってもメモリを消費しません。無限長の配列も定義できます。
#!/usr/bin/python
# -*- coding: utf-8 -*-
def fibsUntil(n):
a = 1
b = 1
yield a
yield b
while True:
tmp = a
a = a + b
b = tmp
if(a >= n):
return
yield a
def Main():
# イテレータの一種であり for 文での利用できます。
for k in fibsUntil(10):
print k
gen = fibsUntil(10)
try:
while True:
# print gen.next() # python 2.x
# print gen.__next__() # python 3.x
print next(gen)
except StopIteration as e:
# StopIteration 例外が発生します。
print "%r" % e
if __name__ == '__main__':
Main()
xrange
range()
はリストを返しますが、xrange()
を利用すると、都度値を generate して返すオブジェクトを作成できます。
range(1,10)
xrange(1,10)
0
記事の執筆者にステッカーを贈る
有益な情報に対するお礼として、またはコメント欄における質問への返答に対するお礼として、 記事の読者は、執筆者に有料のステッカーを贈ることができます。
さらに詳しく →Feedbacks
ログインするとコメントを投稿できます。
関連記事
- Python コードスニペット (条件分岐)if-elif-else sample.py #!/usr/bin/python # -*- coding: utf-8 -*- # コメント内であっても、ASCII外の文字が含まれる場合はエンコーディング情報が必須 x = 1 # 一行スタイル if x==0: print 'a' # 参考: and,or,notが使用可能 (&&,||はエラー) elif x==1: p...
- Python コードスニペット (リスト、タプル、ディクショナリ)リスト range 「0から10まで」といった範囲をリスト形式で生成します。 sample.py print range(10) # for(int i=0; i<10; ++i) ← C言語などのfor文と比較 print range(5,10) # for(int i=5; i<10; ++i) print range(5,10,2) # for(int i=5; i<10;...
- ZeroMQ (zmq) の Python サンプルコードZeroMQ を Python から利用する場合のサンプルコードを記載します。 Fixing the World To fix the world, we needed to do two things. One, to solve the general problem of "how to connect any code to any code, anywhere". Two, to wra...
- Matplotlib/SciPy/pandas/NumPy サンプルコードPython で数学的なことを試すときに利用される Matplotlib/SciPy/pandas/NumPy についてサンプルコードを記載します。 Matplotlib SciPy pandas [NumPy](https://www.numpy
- pytest の基本的な使い方pytest の基本的な使い方を記載します。 適宜参照するための公式ドキュメントページ Full pytest documentation API Reference インストール 適当なパッケージ