列表示例1:
(新建, 删除, 修改)
# basic operation of list
names = ['David', 'George', 'Peter', 'Mark', 'ALice']
print "Original List:"
print names
del names[1]
print "Delete second element:"
print names
names[1] = "Anthony"
print "Change second element:"
print names
names = ['David', 'George', 'Peter', 'Mark', 'ALice']
print "Original List:"
print names
del names[1]
print "Delete second element:"
print names
names[1] = "Anthony"
print "Change second element:"
print names
运行结果:
Original List:
['David', 'George', 'Peter', 'Mark', 'ALice']
Delete second element:
['David', 'Peter', 'Mark', 'ALice']
Change second element:
['David', 'Anthony', 'Mark', 'ALice']
列表示例2:
(分片操作)
-- Python中使用分片操作来访问一定范围内的元素
# -*- coding: cp936 -*-
"""
列表的分片操作
"""
name = list("Perl")
print "Original List From String:"
print name
name[2:] = list("ice")
print "Change elements after second:"
print name
name[2:] = list("ar")
print name
number = [1, 2, 3, 5, 6, 7]
print "Original Number List:"
print number
number.insert(3, "four")
print "Insert before the forth number:"
print number
number.pop()
print "Pop last number:"
print number
number.pop(0)
print "Pop first number:"
print number
number.pop(1)
print "Pop second number:"
print number
"""
列表的分片操作
"""
name = list("Perl")
print "Original List From String:"
print name
name[2:] = list("ice")
print "Change elements after second:"
print name
name[2:] = list("ar")
print name
number = [1, 2, 3, 5, 6, 7]
print "Original Number List:"
print number
number.insert(3, "four")
print "Insert before the forth number:"
print number
number.pop()
print "Pop last number:"
print number
number.pop(0)
print "Pop first number:"
print number
number.pop(1)
print "Pop second number:"
print number
运行结果:
Original List From String:
['P', 'e', 'r', 'l']
Change elements after second:
['P', 'e', 'i', 'c', 'e']
['P', 'e', 'a', 'r']
Original Number List:
[1, 2, 3, 5, 6, 7]
Insert before the forth number:
[1, 2, 3, 'four', 5, 6, 7]
Pop last number:
[1, 2, 3, 'four', 5, 6]
Pop first number:
[2, 3, 'four', 5, 6]
Pop second number:
[2, 'four', 5, 6]
元组示例:
元组是不能被修改的序列
它可以在映射中当作键使用
# tuple sample
print tuple([1, 2, 3])
print tuple('abc')
print tuple((1, 2, 3))
print tuple([1, 2, 3])
print tuple('abc')
print tuple((1, 2, 3))
运行结果:
(1, 2, 3)
('a', 'b', 'c')
(1, 2, 3)