pythonの基本の基本。このエントリをはてなブックマークに追加

3 月 2, 2009

いただいた本をすこーしづつ読みすすめてます。
今回はpythonの基本文法について。
基本文法を習得するにも時間がかかった\(^o^)/
慣れるまでにはもう少し時間かかりそうだなー。関数まわりの奥が深いよ。うん。

今日は文字列、リスト、タプル、辞書、for文あたりについて。

文字列

文字列は、”(ダブルクォーテーション)、’(シングルクォーテーション)で囲めばOK.ヒアドキュメントを使いたい場合は”"”(ダブルクォーテーション*3)、”’(シングルクォーテーション*3)でOK.

>>> l="Hello Python!"
>>> print l
Hello Python!
>>> s='Hello Python'
>>> print s
Hello Python
>>> print """abd
... edg
... eoo"""
abd
edg
eoo
>>> print '''aboel
... eowako
... voeo'''
aboel
eowako
voeo

文字列はオブジェクト扱いになるので、そのまま配列につっこまれたような感じになる。
ので、

>>> s='Hello python!'
>>> print s[1]
e
>>> print len(s)
13

添え字は0からね。

リスト

PHPでいうとこの配列と認識した。
[]で囲めばOK。
追加するのは、extendとappendがあるらしい。動作が微妙に違う。
多重配列の場合は[]の中に[]を書けばOK。
変更するときも、PHPと同じように上書きしてあげればよい。

>>> a=[1,2,3,4,5]
>>> print a
[1, 2, 3, 4, 5]
>>> a.extend(["a","b","c"])
>>> print a
[1, 2, 3, 4, 5, 'a', 'b', 'c']
>>> a.append(["a","b","c"])
>>> print a
[1, 2, 3, 4, 5, 'a', 'b', 'c', ['a', 'b', 'c']]
>>> print a[2]
3
>>> print a[8]
['a', 'b', 'c']
>>> print a[8][1]
b
>>> a[0]=6
>>> print a
[6, 2, 3, 4, 5, 'a', 'b', 'c', ['a', 'b', 'c']]

タプル

タプルとリストの違いがよくわかんなかったんだけど、タプルはPHPでいうとこのdefineみたいな感じかな。
定義後は変更できなくなる。
()で囲めばOK。
リストではないので、追加のextendやappendはない。
追加するときは、タプル+タプルにしてあげる。
もちろんリストのように添え字指定しての変更もできない。

>>> b=(1,2,3)
>>> b.extend(4,)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'extend'
>>> b.append(4,)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
>>> b=b+(4,)
>>> print b
(1, 2, 3, 4)
>>> b[0]=5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

辞書

PHPでいうとこのハッシュ配列。
{key:value}で定義。
変更追加はupdateで行う。
dictでもOK。

>>> d={"a":"b", "c":"d", "e":"f"}
>>> print d
{'a': 'b', 'c': 'd', 'e': 'f'}
>>> d.update({"g":"h"})
>>> print d
{'a': 'b', 'c': 'd', 'e': 'f', 'g': 'h'}
>>> d.update({"a":1})
>>> print d
{'a': 1, 'c': 'd', 'e': 'f', 'g': 'h'}
>>> d2=dict(aaa="bbb",ccc="ddd")
>>> print d2
{'aaa': 'bbb', 'ccc': 'ddd'}

for文

基本は for 添え字 in リストで。色々みたほうがわかりやすいかも。
PHPでいうとforeachに近い?

>>> for i in 1,2,3,4:
...    print i
...
1
2
3
4
>>> s="hello!"
>>> for i in s:
...     print i
...
h
e
l
l
o
!

辞書だとこんな感じ。
PHPでいうとこれ→foreach($array as $key => $val)

>>> a={1:"a", 2:"b", 3:"c"}
>>> for k,v in a.items():
...     print '%s: %s' % (k,v,)
...
1: a
2: b
3: c

イントロスペクション

pythonの勉強がてらMy本棚見てたら、Web+DBPressのVol.46に「速習python」の記事があって、それも読み読み。
dir()のイントロスペクションというのが便利げだ。
そのオブジェクトで、どんな関数が使えるのか表示できる。

>>> d2=dict(aaa="bbb",ccc="ddd")
>>> dir(d2)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> t=(1,2,3)
>>> dir(t)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
>>>
>>>
>>> string="hello"
>>> dir(string)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> a=[1,2,3]
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> t=(1,2,3)
>>> dir(t)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
>>> d={1:"a", 2:"b"}
>>> dir(d)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

という具合。ちょっと長いけど、困ったときとかはいいね!
今日これ書いてたら少しpythonになれてきた。

わかったことは、キーボードが日本語配列だと打ちづらい気がするんだぜ!

Djangoへの道はまだ遠いな・・・。

Categories: python
Tags:

コメントはまだありません »

このコメント欄の RSS フィードトラックバック URL

コメントはまだありません。

コメントをどうぞ