python基礎知識:資料結構的學習

來源:互聯網
上載者:User

標籤:number   形式   sort   長度   ESS   %s   刪除   animal   lan   


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基礎知識:資料結構的學習

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.