Python:列表与字典1-Routine5

列表与元组的区别:元组(tuple)可以含有任意类型数据的序列,但它是不可变的,而列表(list)能做元组能做的任何事情,格式上元组是由一对圆括号包裹,而列表由一对方括号包裹。而且不止这些,列表是可变的,元素可以添加到列表中,也可以把元素从中删除,也能对它进行排序。因此,元组的用法,都可以用到列表上。
以下程序是对列表的一些操作:包括创建列表,对列表遍历,使用len()函数,对列表进行索引,切片,连接,通过列表的可变性,对它进行通过索引赋值,通过切片赋值,还有对列表进行元素的删除,列表切片的删除。

inventory = ["sword","armor","sheild","healing potion"]
print("The item you have:",end = " ")
#print(inventory,end = " ")
for item in inventory:
           print(item,end = " ")
input("\nPress the enter key to continue.")
print("\nYou have",len(inventory),"items in your possession.")
input("\nPress the enter key to continue.")
if "healing potion" in inventory:
           print("\nYou will live to fight another day.")
index = int(input("\nEnter the index number for an item in your inventory:"))
print("At index",index,"is",inventory[index-1],".")
beginnum = int(input("\nEnter the index number to begin a slice:"))
endnum = int(input("Enter the index number to end the slice:"))
print("inventory[",beginnum,":",endnum,"] is",inventory[beginnum-1:endnum-1])
input("\nPress the enter key to continue.")
chest = ["gold","gems"]
print("You find a chest which contains:")
print(chest)
print("\nYou add the contents of chest to your inventory.")
print("Your inventory now is:")
inventory += chest
print(inventory)
input("\nPress the enter key to continue.")
print("You use your gold and gems to buy an orb of future telling.")
inventory[4:6] = ["orb of future telling"]
print("Now your inventory is:",inventory)
input("\nPress the enter key to continue.")
print("In a battle your shield is destroyed.")
del inventory[2]
print("Your inventory is now:",inventory)
input("\nPress the enter key to continue.")
print("You trad your sword for a crossbow.",end = " ")
print("Unfortunately your new crossbow and armor are stolen by detestable thieves ")
inventory[0] = ["crossbow"]
del inventory[:2]
print("Now your inventory is:",inventory)
input("\nPress the enter key to continue.")

列表方法
append(value) : 将value添加到列表末尾
sort() :对元素进行排序,小值在前。可以为reverse参数设置一个布尔值。如果设置的是TRUE,则列表将以“大值在
前”的方式排列顺序。
reverse():反转列表的顺序。
count(value):返回value出现的次数。
index(value):返回value第一次出现的位置编号。
insert(i,value):将value插入到位置i。
pop([i]):返回位置i的值,并将其从列表中删除。也可以不指定位置编号i,这样的话,被删除并返回的就是列表的最后一个元素。
remove(value):删除列表中第一次出现的value。

使用列表方法的例子

Scores = [500,200,300,1000,5000]
print("""
         High Scores
         0----Exit
         1----Show Scores
         2----Add a Score
         3----Remove a Score
         4----Sort Scores
      """)
yourwill = input("\nDo you want to choose from these choices?Yes or No :")
if yourwill.lower() == 'yes':
           choice = int(input("\nEnter your choice:"))
           while choice in range(0,5):
                      if choice == 0:
                                 print("\nYou will exit!")
                                 input("\nPress the enter key to exit!")
                                 break
                      elif choice == 1:
                                 print("\nHigh Scores\n",Scores)
                                 choice = int(input("Choose again?:"))
                      elif choice == 2:
                                 newscore = int(input("\nWhat score did you get?:"))
                                 Scores.append(newscore)
                                 print("Now the new score list is:",Scores)
                                 choice = int(input("Choose again?:"))
                      elif choice == 3:
                                 print("\nNow the score list is:",Scores)
                                 removescore = int(input("Which score do you want to remove from the score list?:"))
                                 if removescore in Scores:
                                            Scores.remove(removescore)
                                            print("Now the new score list is:",Scores)#print里面不能直接将Scores换成Scores.remove(removescore)
                                            choice = int(input("Choose again?:"))
                                 else:
                                            print("The score you give is illegal.")
                                            choice = int(input("Choose again?:"))

                      else :
                                 Scores.sort(reverse = True)
                                 print("\nThe score list that has been sorted is:",Scores)
                                 choice = int(input("Choose again?:"))
           print("The choice is illegal!")

else:
           input("\nPress the enter key to exit!")


猜你喜欢

转载自blog.csdn.net/qq_33158266/article/details/81529892