Python 3.7 -- 數(shù)據(jù)結(jié)構(gòu)--List

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']

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容