HOME > > Python

Python

Python 堺ゃ荀喝∝純c<≪

http://www.python.jp/doc/release/tut/tut.html 沿 http://docs.python.org/tutorial/index.html 祉違с<荀顔≪c沿ャ<潟祉絎祉ャ膊荐

腱∞茹c膣帥ゃ鴻吾醇с篏阪慎

=

篁ヤ紊違荐篏帥紊違荐腓冴吾с羞隙恒ゃ鐚 be assigned to 鐚

Python с= 綏莨冴 x 臀

x=1

x 1腓冴

筝鴻= 綏莨冴臀 x x 腓冴

x=1
print(x)

x 腓冴ゃ障 1 阪

cx y c

y=x

y x 腓冴腓冴

x=1
y=x
print(y)
==> 1

с1+1 Python с綣сeval('1+1') 2 菴x=1 綣ссeval('x=1') 若exec('x=1') 違鐚Python LISP 激潟筝篋阪吾сс≫篋冴荐激潟сゃ潟帥若潟絖違祉鴻http://practical-scheme.net/trans/IsPythonLisp-j.html鐚

絖医

吾сс腓冴сc吾с祉絖贋違

Python 綣茯障Python 絖紊眼с鴻ゃ

>>> a="Hello"
>>> a="Bye"
>>> print a
Bye

сс絖紊眼сa ャ絖腓冴紊眼絖吾蚊綵篏莎激喝帥

絖腟

>>> print 'a' 'bc' 'd'   # 
abcd
>>> s='bc'
>>> print 'a' s 'd'      # 
>>> print 'a' + s + 'd'  # 域
abcd

絖筝鴻翫腟鴻絎茵篁ュ茵с絖絮с絲障+ 篏帥c腟絎茵茵с絮с

絖筝

is 吾с筝腓冴== ゃ筝腓冴

ャゃc絖絖≪сャ吾с篋潟帥

>>> a="dog and cat"
>>> b="dog and cat"
>>> a==b
True
>>> a is b
False

>>> c="dog and cat"
>>> d=c
>>> c is d
True

筝絅絋箴

>>> a="dog"
>>> b="dog"
>>> a is b
True

a 'dog' 蚊綵Python 鴻脂駕intern鐚篏帥絖с篏帥絖ゃ潟帥若潟緇 b 'dog' 蚊綵b a 筝吾с綵≪у

絖紊眼с羞隙恒綣莎激篏茫

>>> a=[1,2]
>>> b=[1,2]
>>> a is b
False

鴻鐚緇菴逸紊眼сラ篏鴻絽吾ャ吾с紊ф祁箙宴莎激

贋違絨違ф宴荀

>>> 1 / 3
0
>>> 1.0 / 3
0.33333333333333331

ゃ贋違筝蚊ゃ絖

>>> a=1
>>> b=1
>>> a==b
True
>>> a is b
True

絨違

>>> a=1.0
>>> b=1.0
>>> a==b
True
>>> a is b
False

篏c荐筝綽荅罨∞

None, False, '', 0, 0.0 ャ吾сс鴻違絮茫羲膊с帥純

c筝с 篏吾с腓冴т 腓冴吾с鴻荀膣若違

=鴻違鴻 = 綏莨冴翫с腴鴻絲障荐с

= 綏莨坂札紊贋篏帥翫吾с茵憗菴違鴻<鴻翫綵障

鴻羞糸

鴻 n 絲障羞糸 n (N=0,1,2,...) a[n] 茵憗сa[n] = 綏莨冴鴻 n+1 吾сャ荐鴻 n+1 荀膣

>>> a=['hello', 'bye']
>>> a[0]
'hello'

筝鴻= 綏莨冴 a[n] 臀翫鴻 n+1 = 勈昇吾с鴻荀膣紊眼鐚帥鐚с

罨<ャ絖鴻篏c罕絖

鴻篌後宍

鴻篌後宍с篌後宍緇吾с筝吾сс

>>> a=[1,2]
>>> b=a
>>> a.append(3)
>>> a
[1,2,3]
>>> b
[1,2,3]

鴻ゃ鴻篏帥茲純

鴻腟 + 若帥c違鴻祉吾с篏c茵

祉違違Python 鴻紊違紊眼с荐ц蟹荐cс

Python 鴻茯LISP cdr 罨<潟潟鴻祉ゃ潟祉筝絮ゃ鴻篌後宍с頫絎茖c荐惹LISP 鴻違緇祉荀膣≪祉鴻激綽荀Python 鴻筝荀膣水ャ翫鴻緇祉水ャ祉祉水ャ羝с絎茖喝с絎潟若腆冴с

筝吾с荀膣ゃャ鴻篏

綽с鴻茲茖純с羌茲茖純若違

翫鴻ゃ刻緇菴逸篏帥c違箴水с

ャ筝鴻

= 綏莨坂札紊贋臀翫吾сс篁ヤャ筝鴻с違筝ゃ鴻荀膣紊眼違鴻ゃ篏帥c鴻荀膣с翫茵c紊眼C с<潟合荐

鴻鐚羞宴鐚潟若

鴻羌潟若荀絲障違鴻cсャ≪ゃ潟ccよ膣鴻篏翫羞宴潟若若吟ゃゃ潟若亥亜茵сャ

鴻ゃ

鴻 L 絲障 L[n:m] L[:] 茵憗鴻ゃ壕羈若違m, n 0 障倶違с鴻筝篏臀茵憗 L=[a,b,c]

|   |   |   |
| a | b | c |
|   |   |   |
0   1   2   3

篏臀腓冴L[:] L[0:鴻泣ゃ] с

障鴻ゃ壕羈ц;憗 = 綏莨冴糸眼荀

L=['a', 'b', 'c', 'd']

L[1:3]=['j', 'k', 'l']

鴻 L 鴻 L[1:3] ['j', 'k', 'l'] 荀膣鴻臀

茖莇潟綏莨冴鴻ゃ鴻= 勈昇鴻帥鐚緇菴逸鐚 iterable 鐚сL[0:1]=1 若

阪慎L=['a', 'b', 'c'] с羞糸篏帥c L[1]=['p','q'] L ['a',['p','q'],'c',] 鴻ゃ鴻篏帥c L[0:1]=['p','q'] с L ['a','p','q','c']

鴻ゃ壕羈ц;憗= 綏莨坂札紊憗翫鴻鴻鐚羌鐚茲茖純篏違鴻鐚LISP 絅処羈鴻鴻с鐚

違荐茯絖吟∽違綣違ゆ検ф検羂Python с絖鴻ц蟹帥吾篋絎号喝ゃ

障絖綣違∽違荅帥

>>> def alterstring (s):
...     s='aho'
... 
>>> x='rikou'
>>> alterstring(x)
>>> print x
rikou

∽違若腥咲x 絖 s 脂蚊

罨< s 違絖 'aho' 紊眼

c x 後 'rikou'

罨<鴻∽違荅帥

>>> def alterlist(t):
...     t[0]='aho'
... 
>>> y=['rikou']
>>> alterlist(y)
>>> print y[0]
aho

∽違若腥咲y 鴻 t 脂蚊

罨< t 鴻膃筝 絖 'aho' 紊眼

cy[0] 'aho' 紊c

綣違

∽違綣違違筝絎с*ゃ篁綣違篏帥絎臂筝с帥篏帥с

>>> def r(a, *b):             # 篁綣 b 篏c綣違綣帥
...     print a
...     for x in b:
...             print x
... 
>>> r(1,2,3)
1
2
3

激с潟違激с潟c純若若綣違篏帥c綣違羝<鴻

>>> def f(a, b):
...     print a
...     print b
... 
>>> f(b=2, a=1)
1
2

筝絎違若若綣違筝** ゃ篁綣違у∽医臂筝с莨吾篏帥

>>> def f(**t):
...     for k in t:
...             print k
...             print t[k]
... 
>>> f(name='Kabi', addr='Aichi')
name
Kabi
addr
Aichi

* ** 羞欠с
http://www.python.jp/doc/release/tut/node6.html#SECTION006720000000000000000
с

Python 鴻鴻篏帥鴻с

# 筝荳
>>> class c:             # 筝荳腥冴
...     pass
... 
>>> c.a=1                # 劫с祉
>>> i=c()                # ゃ潟鴻帥潟剛
>>> i.a2=2               # ゃ潟鴻帥潟劫с祉

剛賢с∽医臂膃筝綣違綽ゃ潟鴻帥潟壕荳膃筝綣違 self 筝膺cc

# 鴻荐荐鐚絮с<純鐚
>>> class c:
...  a=1                # 劫у臂
...  def m(self,x):     # <純絎臂
...    return(self.a+x)
... 
>>> i=c()               # ゃ潟鴻帥潟剛
>>> i.m(2)              # 藥<筝ょ綣違筝荳
3

__init__ 劫ч∽違絎臂ゃ潟鴻帥潟鴻篏絎茵<純

>>> class c:
...     def __init__(self):       # ∽ ___init___ 
...             print(1)
... 
>>> i=c()                         # ゃ潟鴻帥潟剛絎茵
1

膣膓

>>> class p:
...     a=1
... 
>>> class c(p):
...     b=2
... 
>>> i=c()
>>> i.a
1
>>> i.b
2

紊膓

>>> class p1:
...     a=1
... 
>>> class p2:
...     b=2
... 
>>> class c(p1,p2):
...     c=3
... 
>>> i=c()
>>> i.a
1
>>> i.b
2
>>> i.c
3

鐚http://www2.lib.uchicago.edu/keith/courses/python/class/5/ 鐚

箴紊

絖贋違綵吟若若腮蕁翫 ValueError с

>>> int("p")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'p'

違絎茵筝劫腮蕁若榊篏篏try, except 篏帥若罕若阪ャ箴紊若吟 finally 箴紊冴冴緇絎茵

>>> try:
...     int("p")
... except ValueError:
...     print "oops"
... finally:
...     print "bye"
oops
bye

raise 綣桁句箴紊榊с

>>> raise NameError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError

except cсc腮蕁箴紊紊眼鴻

>>> try:
...     try:
...             raise NameError
...     except ValueError:
...             print "I caught the value error"
... except NameError:
...     print "I caught the NameError"
... 
I caught the NameError

while for

while 篁紊荐茯蕁ィfor C for с激с for 罨♂с

ゃ若

ゃ若帥蚊鎀ч荐next() <純<障障с StopIteration 箴紊吾сс

鴻荀膣絖筝絖鴻茯帥鴻翫鴻絖ゃ若帥篏絲障 next() <純違緇障с StopItaration 箴紊

>>> it=iter([1,2,3])
>>> it.next()
1
>>> it.next()
2
>>> it.next()
3
>>> it.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

[ゃ若帥吾с吾с吾 "ゃ潟" 篆с膓<≪蕋≪for 若筝с吾с紊眼鐚ゃ若帥鐚罨≦篁ュ膵違菴綵演帥若]

for 筝吾сゃ若帥吾с緇吾с next <純絎茵n 蚊帥緇 StopIteration 箴紊罩≪

>>> for n in [1,2,3]
>>>    print n
...
1
2
3

篏鴻 __iter__ <純<ゃ若帥ゃ障next() <純<障障с StopIteration 箴紊吾с菴違 for 若т戎菴ゃ若帥荳с障

鴻絲障ゃ若激с潟箴水

鴻絲障ゃ若激с割罐篏帥箴水罧泣障障map, zip, enumerate(list), reduce, 茵, 膈

蚊ゃ鴻腟羲膊絖 + 筝箴綣蕭蕭号荐絖吟

>>> import operator
>>> a=[[1,2],[4,5,6]]
>>> reduce(operator.add,a)
[1,2,3,4,5,6]

篏茫ャ絖鴻茹f鐚flatten=綛潟鐚違亥郡膺馹筝箴茹f鴻ャ絖羞宴狗蕁帥

def flatten(a):
    for n in reversed(range(len(a))):
            if type(a[n])==type([]):
                    flatten(a[n])
                    a[n:n+1]=a[n]

>>> a=[1,[2,[3,[4]]]]
>>> flatten(a)
>>> a
[1, 2, 3, 4]

鴻翫<

鴻篌若鐚

鴻篌若筝荳紊眼с

筝吾潟ャ絖篁ュ篏帥激 1 帥篏羈

# 激 2 帥
t=1,2
t=(1,2)
# 激 1 帥
t=1,
t=(1,)           # t=(1) 医ゃc障
# 激 0 帥
t=()             # t= 罕

帥鴻ャ帥c鴻膓鴻荀膣紊純

>>> a=1
>>> a=[1]
>>> t=(a)
>>> t
[1]
>>> a[0]=2
>>> t
[2]

莨吾腮蕁吾с若ゃ腟篏с若с鴻薈ゃ祉篏с

>>> t={'a':1, 'b':2}                    # 絖若帥
>>> t['a']                              # cゃ冴
1
>>> t={[1,2]:'a', [3,4]:'b'}            # 鴻若
>>> t={(1,2):'a', (3,4):'b'}            # 帥 OK
>>> t[(1,2)]                            # cゃ冴
'a'
>>> t={([1],):'a', ([2],):'b'}          # 鴻膣帥薈

帥若с

>>> t={(1,2):'a', (1,2):'b'}
>>> t[(2-1,1+1)]
'b'

莨吾篏cゃ若帥 next <純若菴

>>> it=iter({'a':1, 'b':2})
>>> it.next()
'a'
>>> it.next()
'b'

for 篏帥c

>>> a={'a':1, 'b':2}
>>> for x in a:
...     print x
...     print a[x]
... 
a
1
b
2

篏帥с

∽違綣違莨吾羝<с

>>> def f(d):
...     for k in d:
...             print k
...             print d[k]
... 
>>> f({'a':1, 'b':2})
a
1
b
2

障с鴻с帥с泣若≪吾ャ若鐚Numeric numarray鐚茯粋昭障篏帥鴻帥篏荀膣絎障帥荀膣吾с鴻篌後宍с

鴻帥荐膊с<篏箴水綏с

絖臀

絖紊眼с<純ゃ膣臀

>>> "xccxccxcc".replace('cc','xx',2)
'xxxxxxxcc'

篁絖絲障<純 http://www.python.jp/doc/release/lib/string-methods.html 吾

罩h頫憗篏帥c臀ラс

罩h頫

Python 罩h頫憗鴻罩h頫憗篏帥c絖臀

絖吾с.臀<純(罩h頫, 臀絖)
ф絖紊眼с
罩h頫憗吾с.臀<純(臀絖, 絲乗院絖)
ф違絖菴c茵隙

import re             # re ≪吾ャ若ゃ潟若
r = re.compile('a')   # 罩h頫憗潟潟ゃ RegexObject ゃ潟鴻帥潟鴻篏
r.sub('d', 'abc')     # ゃ潟鴻帥潟鴻 sub <純篏帥臀腟菴
r.subn('d', 'abc', 1) # sub 鴻臀subn 臀違狗с

鴻激ャ鴻宴若

鴻激ヤゃ茵憗罩h頫憗吾с Python сゃre.compile <純綣違 '\\\\' 茵荐√荀

Perl $variable =~ /regexp/ regexp 罩h頫罩h頫憗с絖筝\\ 罩h頫憗сPerl с鴻激ャ茵憗篏帥с'\\\\' \\ 絖с\\ 罩h頫憗篏帥

筝鴻Python сre.compile(regexp) regexp 罩h頫憗筝с罩h頫憗с絖筝сс'\\\\' 鴻激 2 ゃ吟絖ゃ綣違筝祉

r'\\' 荐羈 '\\\\' 膈с罩h頫憗絖篏遵

Python 絖潟若

激c

潟違

ユ茯潟違潟若絲障馹

鐚http://osksn2.hep.sci.osaka-u.ac.jp/~taku/osx/python/encoding.html鐚

>>> r=re.compile(u'')
>>> m=r.match(u'')
>>> print m.span()
(0,1)

罔羣阪絖障頫腓冴ャ荅宴с

import sys
import codecs
sys.stdout = codecs.getwriter('utf_8')(sys.stdout)
sys.stdin  = codecs.getwriter('utf_8')(sys.stdout)

篁ュ罔羣阪ュユ茯篏帥

<ゃ阪ュ

open <ゃ吾с菴鐚Windows Macintosh 翫rbwb ゃ≪若ゃ祉若帥翫篏帥冴鐚

f=open('/home/baka/a.txt', 'r')

肢水冴絨 r吾莨若水 w茯炊吾 r+菴処 a

潟若c潟違絎

import codecs
f=codecs.open('a.txt', 'r', 'utf_8')

utf_8, euc_jp, shift_jis, etc.

>>> f.read()          # 絎泣ゃ冴吟茯泣ゃ榊ャ莢違翫茯
>>> f.readline()      # 筝茵茯
>>> f.readlines()     # 絎泣ゃ冴よ帥筝茵絎茵鴻

茯水冴絖unicode 吾ссutf EUC c潟若c潟違激鴻с潟潟若ゃ筝鰹str 吾с鐚с荅潟ャ若吾Python 絖潟若

筝茵よャ茯水冴鴻

>>> for line in f:
        print line,

<ゃ吾

f.write('abc\n')

潟若c潟違絎吾

import codecs
f=codecs.open('a.txt', 'w', 'utf_8')

<ゃ

f.close() 

膣違

潟潟ゃ喝違

import sys
arg = sys.argv[1]

激с潟<c茲http://www.python.jp/doc/release/lib/optparse-tutorial.html

純若鴻<ゃ絖絎違吾翫<ゃ

# coding: utf-8

吾違

с荅篏帥c帥

<ゃ筝水≪紊罔羣阪冴帥

# coding: utf-8

import sys, codecs, re

regexp = u'水'
replace = u'≪'
infile=sys.argv[1]

sys.stdout = codecs.getwriter('utf_8')(sys.stdout)
r=re.compile(regexp)
f=codecs.open(infile, 'r', 'utf_8')
b=f.readlines()
for l in b:
	print r.sub(replace, l),
f.close()

[<ゃ吾鴻c阪荐垩сos.path ≪吾ャ若篏帥罩eс]

絎茵腟

$ cat infile.txt 

水

水
$ python test.py infile.txt 

≪

≪

≪吾ャ若c純≪吾ャ若

re с荀篁罔羣≪吾ャ若荀

sqlite3 篏帥c帥

Python ≪吾ャ若絎sqlite3 ≪吾ャ若罔羣сゃ(Python 2.5 篁ュ)靎≦篏帥http://docs.python.org/library/sqlite3.html

>>> import sqlite3                         # ゃゃ潟若
>>> conn = sqlite3.connect('test.sqlite')  # 若帥若鴻
>>> cur = conn.cursor()                    # 若純篏
>>> cur.execute("select * from mytable")   # SQL 肴
<sqlite3.Cursor object at 0xb7d03bc0>
>>> print cur.fetchone()                   # 腟 1 茵吟緇
(u'Mr. Holms', u'111-1111')
>>> print cur.fetchone()                   #  1 茵吟
(u'Dr. Watson', u'222-2222')
>>> print cur.fetchone()                   #  1 茵吟
None
conn.close()                               # 若帥若鴻

sqlite cс靎≦羈鐚若帥若鴻荅峨<ゃ<ゃ篏

SQL 筝莨若翫劫ャ号篏帥違placeholder ? 篏帥篁腟帥 SQL ゃ潟吾с激с潟蚊障莨若障眼吾с帥сcゃ障1 (1,) сc

>>> cur.execute("insert into mytable (name, phone) values(?, ?)", (name,phone))
<sqlite3.Cursor object at 0xb7d03c20>
>>> conn.commit()

絖潟若馹ゃャ若吾Python 絖潟若

type у

>>> type('a')
<type 'str'>

桁茵腓冴с

>>> c=type('a')
>>> c()
''

сtype 菴篏遵ゃ鴻

罨≠
HOME


紕膣
薤藕

茯絖
沿
ユ茯


遵医