天天看點

Python程式設計-基礎知識-清單和元組

清單示例1:

 (建立, 删除, 修改)

# basic operation of list

names = ['David', 'George', 'Peter', 'Mark', 'ALice']

print "Original List:"

print names

del names[1]

print "Delete second element:"

names[1] = "Anthony"

print "Change second element:"

運作結果:

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:"

name[2:] = list("ar")

number = [1, 2, 3, 5, 6, 7]

print "Original Number List:"

print number

number.insert(3, "four")

print "Insert before the forth number:"

number.pop()

print "Pop last number:"

number.pop(0)

print "Pop first number:"

number.pop(1)

print "Pop second 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))

(1, 2, 3)

('a', 'b', 'c')