python Data Structures 數(shù)據(jù)結(jié)構(gòu)有四種,List、無組(Tuple)、字典(Dictionary)和集合(Set);
本章節(jié)主要介紹List
- 使用for進(jìn)行遍歷
- Append
- sort
- del 和 remove
#This is my shopping list
shoplist =['apple','mango','carrot','banana']
print('I have ',len(shoplist),'items to purchase.')
print('These items are:',end=' ')
# for執(zhí)行時相當(dāng)于 shoplist遍歷,并且將每一個選項(xiàng)賦值給item
for item in shoplist:
print(item,end=' ')
print('\nI also have to buy rice.')
#append 增加;在最后增加;
shoplist.append('rice')
print(shoplist)
#append 插入;在第二位插入
shoplist.insert(2,'orange')
print('My shopping list is now',shoplist)
#My shopping list is now ['apple', 'mango', 'orange', 'carrot', 'banana', 'rice']
print('I will sort my list now')
shoplist.sort()
print('Sorted shopping list is',shoplist)
#Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'orange', 'rice']
print('The first item I will buy is ',shoplist[0])
#My shopping list is now ['carrot', 'mango', 'orange', 'rice']
olditem =shoplist[0]
#刪除一個選項(xiàng) del shoplist[0] 也可以使用remove.shoplist[0]
del shoplist[0]
print('I bought the ',olditem)
#I bought the apple
print('My shopping list is now',shoplist)
#My shopping list is now ['banana', 'carrot', 'mango', 'orange', 'rice']
olditem =shoplist[0]
shoplist.remove(olditem);
print('I bought the ',olditem)
#I bought the banana
print('My shopping list is now',shoplist)
#My shopping list is now ['carrot', 'mango', 'orange', 'rice']