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!")
相關推薦
Python:列表與字典1-Routine5
列表與元組的區別:元組(tuple)可以含有任意型別資料的序列,但它是不可變的,而列表(list)能做元組能做的任何事情,格式上元組是由一對圓括號包裹,而列表由一對方括號包裹。而且不止這些,列表是可變的,元素可以新增到列表中,也可以把元素從中刪除,也能對它進行排
python 之 列表與字典
ppi 實現 for 對象的引用 false key default abc sid 1.4 列表與字典 列表與字典,這兩種類型,都是各種類型的集合,以列表為例,如果列表中包含列表,就形成嵌套。 這兩種類型幾乎是所有python腳本的主要工作組件 。 這種結構信息是可變
Python基礎學習二:列表,字典,深拷貝與淺拷貝
④使用pop()方法刪除元素:pop方法用於移出列表中的一個元素(預設是最後一個元素),可以指定元素索引,並且返回該元素的值。 使用del語句刪除元素:如果知道要刪除的元素在列表中的位置,可使用del語句刪除元素,元素一旦被刪除之後就再也無法訪問。
python--列表與字典
python基礎列表與字典是其他對象類型的集合。一、內置對象---list(列表),可以包含數字、字符串或其他列表。其屬性主要有 1.任意對象的有序集合,列表就是收集其他對象的地方,同時是有位置順序的。 2.通過偏移讀取 3.可變長度、異構和任意嵌套 4
python 列表與字典相互轉換
bubuko 內置函數 sin 技術 for 分享圖片 ima 字符 復數類 1. 2個列表轉換為字典 #encoding=utf-8list1=["a","b","c"]list2=[1,2,3]d={}for i in range(len(list1)): d[l
#學習筆記Python#7、列表 字典(12下)&8、列表與字典 (第12章掃尾)&9、函式(13)
7、列表 字典(12下) 2017-08-09 19:14 查詢索引(為了找到一個元素位於列表中的什麼位置) 暫時沒有找到方法。。。。。 迴圈處理列表 letters=["a","b","d","e"] for letter in letters: pr
python: 列表 + 字典 + 向json檔案追加資料
在關於影象的深度學習中,我們有影象和對應的標籤。通常我們將影象名字和對應的標籤寫在json檔案中,通過字典的方式進行編碼。我們可以看一個例子: [{“disease_class”: 1, “image_id”: “1.jpg”}, {“disease_class”: 2, “image_
python零基礎入門day2--列表與字典
如果我們想要儲存一堆具有相同性質的資料的時候應該怎麼做?比如說現在我想用python儲存一個班裡所有同學的資訊,我該怎麼儲存?難道要一個一個建立變數來儲存嗎?這樣實在是太笨了,如果我想要儲存整個學校同學的名單,那還不得累死。python中有這麼些資料結構,可以幫
Python之列表轉字典:setdefault、defaultdict、fromkeys
setdefault result = {} data = [("p", 1), ("p", 2), ("p", 3), ("h", 1), ("h", 2), ("h", 3)] for (key, value) in data: result.setdefault(key,
python 列表與字典轉換
一、列表轉字典: 方法1: list_1 = ['abc', 'efg'] list_2 = [123, 456] new_dict = dict(zip(list_1, list_2)) 方法2: list_1 = ['a', 1]
Python學習筆記(六):列表和字典
以Mark Lutz著的《Python學習手冊》為教程,每天花1個小時左右時間學習,爭取兩週完成。 --- 寫在前面的話 2013-7-18 19:00 學習筆記 1,Python中的列表是任意物件的有序集合,而且是可變的。在標準的Python直譯器內部,列表是C陣列,不
Python:列表值為字典
大腦一不運轉,就幹啥都不得勁,這幾天中秋節,“閒”有了,又開始搗鼓程式設計。這裡碰到個低階問題,跟大家分享一下,大家一定要引以為戒,因為當花了不少時間終於解決問題時,我自己都恍然大笑,要不是為了維持形象,都想抽自己。 語言:Python(AI必備) 問題及基本知識描述: 在
Python 7 列表 for 字典,嵌套
功能 python 結果 guest arm 表示 bsp 第一個 必須 列表: 基本格式:變量名 = [元素1,元素2,元素3] 創建:A = [‘訪客‘,‘admin‘,19] 或 A = list([‘armin‘,‘admin‘,19]), 後者更傾向
while循環 操作列表與字典
upper rep 用戶 所有 之前 現在 ref you 特定 1、在列表間移動元素 #!/usr/bin/env python #filename=list.py num1 = [1,3,5,7,9,11,13,15] num2 = [] while num1:
robotframework的列表與字典
appium 字典 blog width log selenium2 mage ges -1 這裏以Get Element Size為例,Selenium2Library返回的是列表,AppiumLibrary返回的是字典。 列表用 ${width}獲取;字典用 &
第二章:列表與元素
擴展 不可變 數據結構--棧 需求 帳號 追加 line -h 隱式 本章將引入一個新的概念:數據結構。數據結構是通過某種方式(例如對元素進行編號)組織在一起的數據元素的集合。這些數據元素可以是數字或者字符,甚至可以是其他數據結構。在python中,最基本的數據結構是序列。
列表與字典
逗號 friends 總結 本質 定義 pri [] color body 列表: 類型總結: 1,可以存多個任意的值 2,有序的 3,可變 列表與字符串相似處:都可以按照索引取值,都是有序的 定義:[]內可以有多個任意類型的值,逗號分隔 my_girl_friends=[
ptyhon的列表與字典操作
python 列表和字典列表是Python中最基本的數據結構。列表中的每個元素都分配一個數字 - 它的位置,或索引,第一個索引是0,第二個索引是1,依此類推。列表都可以進行的操作包括索引,切片,加,乘,檢查成員。在Python中列表中可以有多個類型的數據。eg list1 = ['physics&
python 使用列表和字典存儲信息
ear ict nbsp 車輛 存儲 color car def inventory """ 作者:白 時間:2018年1月9日 需求:假設你很多汽車,通過不斷詢問您是否要將車輛添加到您的庫存中, 如果您這樣做,
Python(二)列表與操作
添加 選擇刪除 創建 dex 包含 sap 第一個元素 index end 1.列表的創建 alist = [123,‘abc‘,4.56,[‘inner‘,‘list‘],‘Dchen‘,‘Blank sapce‘] #方刮號為列表,裏面的的數組視自己情況添加 2.