元组、字典、序列、对象与参考
例一:
元组:不可变,圆括号里面的逗号
和列表十分类似,只不过元组和字符串一样是 不可变的 即你不能修改元组,元组通过圆括号中用逗号分割的项目定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。
#!/usr/bin/python # Filename: using_tuple.py zoo = ('wolf', 'elephant', 'penguin') print 'Number of animals in the zoo is', len(zoo) new_zoo = ('monkey', 'dolphin', zoo) print 'Number of animals in the new zoo is', len(new_zoo) print 'All animals in new zoo are', new_zoo print 'Animals brought from old zoo are', new_zoo[2] print 'Last animal brought from old zoo is', new_zoo[2][2]
例二:
字典:键值对。d = {key1 : value1, key2 : value2 }
字典类似于你通过联系人名字查找地址和联系人详细情况的地址簿,即,我们把键(名字)和值(详细情况)联系在一起。注意,键必须是唯一的
#-*-encoding:utf-8-*- #!/usr/bin/env python # Filename: using_dict.py # 字典类似于你通过联系人名字查找地址和联系人详细情况的地址簿,即,我们把键(名字)和值(详细情况)联系在一起。 #注意,键必须是唯一的,就像如果有两个人恰巧同名的话,你无法找到正确的信息 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'] # 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']
例三、序列
列表、元组和字符串都是序列,但是序列是什么,它们为什么如此特别呢?序列的两个主要特点是索引操作符和切片操作符。
#!/usr/bin/env python # Filename: seq.py shoplist=['apple','mango','carrot','banana'] # Indexing or 'Subscription' operation print 'Item 0 is', shoplist[0] print 'Item 1 is', shoplist[1] print 'Item 2 is', shoplist[2] print 'Item 3 is', shoplist[3] print 'Item -1 is', shoplist[-1] print 'Item -2 is', shoplist[-2] # Slicing on a list print 'Item 1 to 3 is', shoplist[1:3] print 'Item 2 to end is', shoplist[2:] print 'Item 1 to -1 is', shoplist[1:-1] print 'Item start to end is', shoplist[:] # Slicing on a string name='swaroop' print 'characters 1 to 3 is', name[1:3] print 'characters 2 to end is', name[2:] print 'characters 1 to -1 is', name[1:-1] print 'characters start to end is', name[:]
例四 参考:(指向)
#!/usr/bin/env python # Filename: reference.py print 'Simple Assignment' shoplist=['apple','mango','carrot','banana'] mylist=shoplist # mylist is just another name pointing to the same object! del shoplist[0] #del mylist[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