1. 程式人生 > >python基礎知識:數據結構的學習

python基礎知識:數據結構的學習

字符串 [1] script uid nim value operation 字符 index


python的數據結構有:列表、元組、字典

列表:
作用:處理 有序 項目的數據結構
list=["a",‘b‘,‘v‘,‘d‘]
# 打印長度
print(len(list))
# 循環打印
for i in list:
print i
# 在序列最後插入數據
list.append("5")
for i in list:
print i
print(list[0])
# 刪除序列中的某個元素
del list[0]
print(list[0])
# 對列表進行排序
list.sort()
print(list)

元組
作用:同列表類似
區別:元組不可變,不可被修改
# 使用元組
zoo = (‘wolf‘, ‘elephant‘, ‘penguin‘)
print ‘Number of animals in the zoo is‘, len(zoo)
new_zoo = (‘monkey‘, ‘dolphin‘, zoo)
print ‘Number of animals in the new zoo is‘, len(new_zoo)
print ‘All animals in new zoo are‘, new_zoo
print ‘Animals brought from old zoo are‘, new_zoo[2]
print ‘Last animal brought from old zoo is‘, new_zoo[2][2]

字典
作用:鍵和值聯系。鍵是唯一的。沒有順序。
標記形式:d = {key1 : value1, key2 : value2 }
# 使用字典
ab = { ‘Swaroop‘ : ‘[email protected]‘,
‘Larry‘ : ‘[email protected]‘,
‘Matsumoto‘ : ‘[email protected]‘,
‘Spammer‘ : ‘[email protected]
}
print "Swaroop‘s address is %s" % ab[‘Swaroop‘]
66
# Adding a key/value pair
ab[‘Guido‘] = ‘[email protected]
# Deleting a key/value pair
del ab[‘Spammer‘]
len(ab)
for name, address in ab.items():
print (name, address)

序列:
包括:列表、元組、字符串
特點:索引操作符、切片操作符
使用:
# 使用序列
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 = ‘swaroop‘
print ‘characters 1 to 3 is‘, name[1:3]
print ‘characters 2 to end is‘, name[2:]
print ‘characters 1 to -1 is‘, name[1:-1]
print ‘characters start to end is‘, name[:]

字符串的使用:
# 字符串使用
name = ‘Swaroop‘ # This is a string object
if name.startswith(‘Swa‘):
print ‘Yes, the string starts with "Swa"‘
if ‘a‘ in name:
print ‘Yes, it contains the string "a"‘
if name.find(‘war‘) != -1:
print ‘Yes, it contains the string "war"‘
delimiter = ‘_*_‘
mylist = [‘Brazil‘, ‘Russia‘, ‘India‘, ‘China‘]
print delimiter.join(mylist)

python基礎知識:數據結構的學習