Chinaunix首页 | 论坛 | 博客
  • 博客访问: 209683
  • 博文数量: 76
  • 博客积分: 2231
  • 博客等级: 大尉
  • 技术积分: 826
  • 用 户 组: 普通用户
  • 注册时间: 2011-10-27 09:15
文章分类

全部博文(76)

文章存档

2011年(76)

分类: Python/Ruby

2011-11-24 09:34:44


序列
列表、元组和字符串都是序列,但是序列是什么,它们为什么如此特别呢?序列的两个主要特点是索引操作符和切片操作符。索引操作符让我们可以从序列中抓取一个特定项目。切片操作符让我们能够获取序列的一个切片,即一部分序列。
#!/usr/bin/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 = 'sawroop'
print 'charactors 1 to 3 is', name[1:3]
print 'charactors 2 to end is', name[2:]
print 'charactors 1 to -1 is', name[1:-1]
print 'charactors start to end is', name[:]

记住,Python从0开始计数。因此,shoplist[0]抓取第一个项目,shoplist[3]抓取shoplist序列中的第四个元素。
索引同样可以是负数,在那样的情况下,位置是从序列尾开始计算的。因此,shoplist[-1]表示序列的最后一个元素而shoplist[-2]抓取序列的倒数第二个项目。
切片操作符是序列名后跟一个方括号,方括号中有一对可选的数字,并用冒号分割。注意这与你使用的索引操作符十分相似。记住数是可选的,而冒号是必须的。

这样,shoplist[1:3]返回从位置1开始,包括位置2,但是停止在位置3的一个序列切片,因此返回一个含有两个项目的切片。类似地,shoplist[:]返回整个序列的拷贝。
使用Python解释器交互地尝试不同切片指定组合,即在提示符下你能够马上看到结果。序列的神奇之处在于你可以用相同的方法访问元组、列表和字符串。

参考
当你创建一个对象并给它赋一个变量的时候,这个变量仅仅 参考 那个对象,而不是表示这个对象本身!也就是说,变量名指向你计算机中存储那个对象的内存。这被称作名称到对象的绑定。
一般说来,你不需要担心这个,只是在参考上有些细微的效果需要你注意。这会通过下面这个例子加以说明。
对象与参考
#!/usr/bin/python
# Filename: reference.py

print 'Simple Assignment'
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointingto the same object!

#del mylist[0]
del shoplist[0]

print 'shoplists is', shoplist
print 'mylist is', mylist
# notice that both shoplist and mylist both print thesame list without# the 'apple' confirming that they point to the sameobject

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
你需要记住的只是如果你想要复制一个列表或者类似的序列或者其他复杂的对象(不是如整数那样的简单 对象 ),那么你必须使用切片操作符来取得拷贝。如果你只是想要使用另一个变量名,两个名称都 参考 同一个对象,那么如果你不小心的话,可能会引来各种麻烦。

阅读(1018) | 评论(0) | 转发(0) |
0

上一篇:字典

下一篇:更多字符串内容

给主人留下些什么吧!~~