python学习笔记(三)

1) 模块。 一个单独的.py文件,就是一个模块,可以用import关键字来引入模块(不需要输入.py后辍)。模块中定义的函数和变量,可以通过“模块名.函数名”,“模块名.变量名"来访问。
====================================
# demo.py
def test():
~print "hi"

str = "hello"


#demo2.py
import demo
demo.test()             #=> hi
print demo.str         #=> hello
====================================

使用import,在使用的时候还是需要使用“模块名.函数名”,“模块名.变量名”,使用from .. import就可以直接使用函数名和变量名了。
====================================
# demo.py
def test():
~print "hi"

str = "hello"


#demo2.py
from demo import test,str
test()             #=> hi
print str         #=> hello
====================================

2) dir()。 dir函数是用来显示模块的所有函数和变量的。它可以接收模块名作为参数,也可以不接收参数,如果不接收参数,表示显示当前模块。

3) 数组(列表)。 python中数组的使用方式和js类似,["a","b","c"]。数组的长度是用len()函数来得到的,删除用del arr[index],添加用append(),不是push()真奇怪。
=======================
a = ["a","b","c"]
print len(a)                      #=> 3
a.append("d")        
print a                             #=> ["a","b","c","d"]
del a[2]
print a                             #=> ["a","b","d"]
for i in a :
~ print i,                          #=> a b d
=======================

4) 元组。 元组和数组(列表)非常像,同样用len()返回长度,同样用[index]访问序列中指定位置的元素。不同的是元组是不变对象,它不能像数组一样改动。元组的界定符是()。
===============================
zoo = ('wolf', 'elephant', 'penguin')
print 'Number of animals in the zoo is', len(zoo)              #=> 3

new_zoo = ('monkey', 'dolphin', zoo)
print 'Number of animals in the new zoo is', len(new_zoo)      #=> 3
print 'All animals in new zoo are', new_zoo                    #=> ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))
print 'Animals brought from old zoo are', new_zoo[2]           #=> ('wolf', 'elephant', 'penguin')
print 'Last animal brought from old zoo is', new_zoo[2][2]          #=> penguin
===============================

5) 字典(hash)。 python中字典的形式和js中一样,和ruby不同,但调用时和ruby一样,只能通过[]来调用,不能像js那样用.来调用。和js不同,python中字典可以调len()函数来查看长度。
=============================
ab = {       'Swaroop'   : 'swaroopch@byteofpython.info',
             'Larry'     : 'larry@wall.org',
             'Matsumoto' : 'matz@ruby-lang.org',
             'Spammer'   : 'spammer@hotmail.com'
     }

print "Swaroop's address is %s" % ab['Swaroop']         #=> swaroopch@byteofpython.info

# Adding a key/value pair
ab['Guido'] = 'guido@python.org'

# Deleting a key/value pair
del ab['Spammer']

print '\nThere are %d contacts in the address-book\n' % len(ab)
for name, address in ab.items():
    print 'Contact %s at %s' % (name, address)

if 'Guido' in ab: # OR ab.has_key('Guido')
    print "\nGuido's address is %s" % ab['Guido']

=============================

6) 序列。 在python中元组、列表和字符串都属于序列。序列都可以通过索引找到相应位置的元素,也可以进行截取。和ruby一样,python中的序列支持负数作为索引。截取是通过[n:m]进行的,比js的slice方法方便。
=============================
shoplist = ['apple', 'mango', 'carrot', 'banana']

# Indexing or 'Subscription' operation
print 'Item 0 is', shoplist[0]             #=> apple
print 'Item 1 is', shoplist[1]      #=> mango
print 'Item 2 is', shoplist[2]      #=> carrot
print 'Item 3 is', shoplist[3]      #=> banana
print 'Item -1 is', shoplist[-1]    #=> banana
print 'Item -2 is', shoplist[-2]    #=> carrot

# Slicing on a list
print 'Item 1 to 3 is', shoplist[1:3]             #=> ["manago","carrot"]
print 'Item 2 to end is', shoplist[2:]                        #=> ['carrot', 'banana']
print 'Item 1 to -1 is', shoplist[1:-1]           #=> ['mango', 'carrot']
print 'Item start to end is', shoplist[:]                  #=> ['apple', 'mango', 'carrot', 'banana']

# Slicing on a string
name = 'swaroop'
print  name[2]                                                                              #=> a
print 'characters 1 to 3 is', name[1:3]           #=> wa
print 'characters 2 to end is', name[2:]          #=> aroop
print 'characters 1 to -1 is', name[1:-1]         #=> waroo
print 'characters start to end is', name[:]       #=> swaroop
=============================

7) 传值和传址。 如果你想要复制一个列表或者类似的序列或者其他复杂的对象(不是如整数那样的简单 对象 ),那么你必须使用切片操作符来取得拷贝。如果你只是想要使用另一个变量名,两个名称都 参考 同一个对象,那么如果你不小心的话,可能会引来各种麻烦。这个和js怎么一模一样啊?对于写惯了js的我来说,亲切到想哭。
=============================
print 'Simple Assignment'
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the same object!

del shoplist[0]

print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that both shoplist and mylist both print the same list without
# the 'apple' confirming that they point to the same object


print 'Copy by making a full slice'
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0] # remove first item

print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that now the two lists are different
=============================

8) 字符串对象。 字符串对象有一些奇怪的方法,例如startswith()。判断字符串中是否含有某个子字符串,不是用indexOf(),而是用find()方法,同样的,返回-1表示不在字符串中。另外,还可以用in来进行判断。最让人受不了的是join()方法居然是字符串的,而不是数组的!!
=============================
name = 'Swaroop' # This is a string object

if name.startswith('Swa'):
    print 'Yes, the string starts with "Swa"'

if 'a' in name:
    print 'Yes, it contains the string "a"'

if name.find('war') != -1:
    print 'Yes, it contains the string "war"'

delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print delimiter.join(mylist)      #=> Brazil_*_Russia_*_India_*_China
=============================
posted on 2010-07-10 23:24  真阿当  阅读(109)  评论(0编辑  收藏  举报