GoodZhang在学Python(九)--序列和参考

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhdl11/article/details/38758325

序列

什么是序列呢?是一种数据存储结构,成员是有序排列的,可以通过下标偏移量来访问其成员。字符串、列表、元组都是序列。

序列主要有两个特点,索引和切片,顾名思义,通过索引操作我们可以抓取其中某特定项目,通过切片操作可以抓取一段序列

通过例子体会一下:

__author__ = 'zWX231671'

testlist = ['kobe', 'james', 'KG', 'paul', 'allen']
# slice on a list
print('Testlist is: ', testlist)
print('item 1 to 4', testlist[1:4])
print('item 1 to end', testlist[1:])
print('item 1 to -1', testlist[1:-1])

# slice on a string
teststring = 'abcdefghijklmn'
print('\nTest String is:', teststring)
print('string 1 to 4: ', teststring[1:4])
print('string 1 to end: ', teststring[1:])
print('string 1 to -2: ', teststring[1:-2])
print('string start to end: ', teststring[:])
结果:

Testlist is:  ['kobe', 'james', 'KG', 'paul', 'allen']
item 1 to 4 ['james', 'KG', 'paul']
item 1 to end ['james', 'KG', 'paul', 'allen']
item 1 to -1 []

Test String is: abcdefghijklmn
string 1 to 4:  bcd
string 1 to end:  bcdefghijklmn
string 1 to -2:  bcdefghijkl
string start to end:  abcdefghijklmn
例子很简单,看一下就明白了。


参考

 当创建一个对象,并给其赋一个变量时,这个变量仅仅是参考了这个对象,并不表示对象本身,也就是说,变量名指向计算机中存储那个对象的内存。这被称作名称到对象的绑定

例子:

__author__ = 'zWX231671'
# 变量名 nbaplayer cbaplayer仅仅是参考了对象,指向了其在计算机中的内存,不表示对象本身
nbaplayer = ['kobe', 'james', 'zhdl', 'zhonghuan']
cbaplayer = nbaplayer

print('the original list of nbaplayer:', nbaplayer)
print('the original list of cbaplayer:', cbaplayer)

del nbaplayer[0]
# 输出结果是一致的,说明两个名字是指向计算机内部同一块内存的
print('del nbaplayer[0],the rest list of nbaplayer:', nbaplayer)
print('del nbaplayer[0],the rest list of cbaplayer:', cbaplayer)

abaplayer = nbaplayer[:]
del nbaplayer[0]
print('copy by silce,\n'
      'nbaplayer are:', nbaplayer,
      '\nabaplayer are:', abaplayer)
# 列表的赋值语句不是创建拷贝,需要使用切片操作来创建拷贝
# 如果需要copy列表或者类似的序列或者其他负责的对象,需要使用切片操作来copy对象
输出结果:

the original list of nbaplayer: ['kobe', 'james', 'zhdl', 'zhonghuan']
the original list of cbaplayer: ['kobe', 'james', 'zhdl', 'zhonghuan']
del nbaplayer[0],the rest list of nbaplayer: ['james', 'zhdl', 'zhonghuan']
del nbaplayer[0],the rest list of cbaplayer: ['james', 'zhdl', 'zhonghuan']
copy by silce,
nbaplayer are: ['zhdl', 'zhonghuan'] 
abaplayer are: ['james', 'zhdl', 'zhonghuan']



猜你喜欢

转载自blog.csdn.net/zhdl11/article/details/38758325
今日推荐