Python 3.7 -- 数据结构--List

python Data Structures 数据结构有四种,List、无组(Tuple)、字典(Dictionary)和集合(Set);
本章节主要介绍List

  • 使用for进行遍历
  • 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执行时相当于 shoplist遍历,并且将每一个选项赋值给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]
#删除一个选项 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']

你可能感兴趣的:(Python 3.7 -- 数据结构--List)