首页 > 代码库 > python 学习笔记 3 -- 数据结构篇下
python 学习笔记 3 -- 数据结构篇下
5.引用
当你创建一个对象并给它赋一个变量的时候,这个变量仅仅 引用 那个对象,而不是表示这个对象本身!也就是说,变量名指向你计算机中存储那个对象的内存。这被称作名称到对象的绑定。
eg.
[python] view plaincopy
# -*- coding: utf-8 -*-
shoplist = [‘apple‘, ‘mango‘, ‘carrot‘, ‘banana‘]
print "we copy the shoplist to mylist directly \"with mylist = shoplist\" "
mylist = shoplist # 直接使用等于,此时mylist与shoplist只是指向一个对象的两个名字
print "\tNow the shoplist is : %s"% shoplist
print "\tNow the mylist is : %s"% mylist
print "delete the first item of shoplist"
del shoplist[0] # 此时删除shoplist 或者mylist 中的元素效果是一样的,都会对那个列表对象直接进行操作
print "\tNow the shoplist is : %s"% shoplist
print "\tNow the mylist is : %s"% mylist
print "\nThis time we use slice to cope the shoplist \"with mylist = shoplist[:]\" "
mylist = shoplist[:] # 使用一个完整的切片复制,此时mylist只是与shoplist有一样的内容的两个对象!
print "delete the first item of mylist"
del mylist[0] # 此时删除mylist中的元素不会对shoplist中的元素造成影响!
print "\tNow the shoplist is : %s"% shoplist
print "\tNow the mylist is : %s"% mylist
运行的结果如下:
[plain] view plaincopy
long@zhouyl:~/python_test$ python cite.py
we copy the shoplist to mylist directly "with mylist = shoplist"
Now the shoplist is : [‘apple‘, ‘mango‘, ‘carrot‘, ‘banana‘]
Now the mylist is : [‘apple‘, ‘mango‘, ‘carrot‘, ‘banana‘]
delete the first item of shoplist
Now the shoplist is : [‘mango‘, ‘carrot‘, ‘banana‘]
Now the mylist is : [‘mango‘, ‘carrot‘, ‘banana‘]
This time we use slice to cope the shoplist "with mylist = shoplist[:]"
delete the first item of mylist
Now the shoplist is : [‘mango‘, ‘carrot‘, ‘banana‘]
Now the mylist is : [‘carrot‘, ‘banana‘]
6.字符串的方法
字符串也是对象,同样具有方法。这些方法可以完成包括检验一部分字符串和去除空格在内的各种工作。
eg.
[python] view plaincopy
# -*- coding: utf-8 -*-
name = ‘longerzone‘ # 先定义一个字符串
if name.startswith(‘lon‘): # startwith 用来测试字符串是否以给定字符串开始。
print ‘Yes, the string starts with "lon"‘
if ‘z‘ in name: # in操作符用来检验一个给定字符串是否为另一个字符串的一部分
print ‘Yes, it contains the string "z"‘
if name.find(‘zon‘) != -1: # find方法用来找出给定字符串在另一个字符串中的位置,或者返回-1以表示找不到子字符串。
print ‘Yes, it contains the string "zon"‘
delimiter = ‘_*_‘
mylist = [‘Brazil‘, ‘Russia‘, ‘India‘, ‘China‘]
print delimiter.join(mylist) # str类也有以一个作为分隔符的字符串join序列的项目的整洁的方法,它返回一个生成的大字符串。
这里的运行结果如下:
[plain] view plaincopy
<span style="font-size:18px;">long@zhouyl:~/python_test$ python string.py
Yes, the string starts with "lon"
Yes, it contains the string "z"
Yes, it contains the string "zon"
Brazil_*_Russia_*_India_*_China
</span>
注:本文主要以例子的形式介绍了几种python的数据结构,只能作为简单了解,想跟熟悉使用还需您自己好好练习,多阅读好代码!