返回列表 發帖

串列 (一)

本帖最後由 鄭繼威 於 2024-7-9 09:35 編輯

• 串列,又稱為「清單」或「列表」,與其他語言的
「陣列(Array)」相同,其功能與變數相類似。
  索引值是從0 開始計數,索引值不可超出串列的範圍
• 宣告
串列名稱(變數名稱)= [元素1, 元素2, ......]
• 範例
list1 = [1, 2, 3, 4, 5]
#元素皆為整數
list2 = ["香蕉", "蘋果", "橘子"]
#元素皆為字串
list3 = [1, "香蕉", True]
#包含不同資料型態元素

• 取得串列元素
變數名稱= 串列名稱[索引值]


假設有一串列其內容如下:
list=["忠","孝","仁","愛","信","義","和","平"]

試取出串列中的第1到第5個元素

  1. list=["忠","孝","仁","愛","信","義","和","平"]
  2. print(list[0])
  3. print(list[1:6]) #左邊是開始(有包含),右邊是結束(沒有包含)。
  4. print(list1[-1]) #取出最後一個元素值
複製代碼

  1. list=["忠","孝","仁","愛","信","義","和","平"]

  2. print(list[0:4])
  3. print(list[4:8])
  4. print(list[7:8])
  5. print(list[0:8])
  6. print(list[0:10:2])
  7. print(list[::2])
  8. print(list[::-1])
  9. print(list[::-2])
  10. print(list[1::2])
  11. print(list[1:9:2])
  12. print(list[-4:-1])
複製代碼

TOP

  1. list=["忠","孝","仁","愛","信","義","和","平"]
  2. print(list[0])
  3. print(list[1:6])
  4. print(list[-1])
  5. list1 = [1, 2, 3, 4, 5]
  6. list00 = [1, "香蕉", 3, 4, 5]
複製代碼

TOP

list[1,56,3543,5536.46543231,486,87630]
print(list[1:5])

TOP

  1. list=["忠","孝","仁","愛","信","義","和","平"]
  2. print(list[1:6])
複製代碼

TOP

  1. list=["忠","孝","仁","愛","信","義","和","平"]
  2. print(list[-5:-2])
  3. print(list[0])
複製代碼

TOP

  1. list=["忠","孝","仁","愛","信","義","和","平"]
  2. print(list[0])
  3. print(list[0:8])
  4. print(list[-2])
複製代碼

TOP

  1. list=["忠","孝","仁","愛","信","義","和","平"]
  2. print(list[1:5])
  3. print(list[-1])
複製代碼

TOP

  1. list = ['歐克','萌新','別府','仁美','萬代','公正','時雨','敦文','魚日','卡米克']

  2. print(list[0]) #第一項是0號
  3. print(list[9]) #最後一個是9號,也就是10號前一個
  4. print(list[0:10]) #0號到10號前一個
  5. print(list[0:-4]) #0號到倒數第4個
  6. print(list[:10]) #開始到10號前一個
  7. print(list[:-3]) #後三個不要
  8. print(list[3:])  #三號以前的不要
複製代碼

TOP

  1. list=[1,2,3,4,5,6,7,8,9,10]
  2. print(list[3])
  3. print(list[3:11])
  4. print(list[-7:-2])
複製代碼

TOP

  1. list=["忠","孝","仁","愛","信","義","和","平"]
  2. print(list[0])
  3. print(list[1:6]) #左邊是開始(有包含),右邊是結束(沒有包含)。
  4. print(list1[-1]
複製代碼

TOP

  1. list=['忠,孝,仁,義,愛']
  2. print(list[0:3])      
  3.       
複製代碼

TOP

返回列表