Skip to main content

List 清單

清單是任何類型元素的序列,並且是可變的。用於儲存項目集合,它們可以包含任何型別的資料,並以方(中)括號表示。

a = [1, 2, 3, 4, 5]
b = ['mango', 'pineapple', 'orange']

在 Python 中,List 和 String 非常相似。它們都是資料序列的範例。序列有類似的屬性,例如:

  1. 可以使用 for 迴圈迭代序列
  2. 支援索引 indexing 
  3. 使用 len() 函數找出序列的長度
  4. 使用加號運算符 + 來串連
  5. 使用 in 關鍵字來檢查序列是否包含一個值

List 與 String 的差異是,String 內容是不可變的 (immutable);List 內容可以變動 (mutable)。

List methods

list.append()
numbers = [1, 2, 3, 4]
numbers.append(5)
print(numbers)
 
# output: [1, 2, 3, 4, 5]
list.insert()
animals = ["cat", "dog", "fish"]
animals.insert(1, "monkey")
print(animals)
 
# output: ["cat", "monkey", "dog", "fish"]

animals = ["cat", "dog", "fish"]
animals.insert(200, "monkey")
print(animals)
 
# output: ["cat", "dog", "fish", "monkey"]
list.extend()
things = ["John", 42, True]
other_things = [0.0, False]
things.append(other_things)
print(things)
 
# output: ["John", 42, True, [0.0, False]]

things = ["John", 42, True]
other_things = [0.0, False]
things.extend(other_things)
print(things)
 
# output: ["John", 42, True, 0.0, False]
list.remove()
Note: If there are two of the same element in a list, the .remove() method only removes the first instance of that element and not all occurrences.
booleans = [True, False, True, True, False]
 
booleans.remove(False)   # Removes the first False value
print(booleans)
 
# output: [True, True, True, False]
 
booleans.remove(False)   # Removes the other False value
print(booleans)
 
# output: [True, True, True]
 
booleans.remove(False)   # ValueError! No more False values to remove
list.pop()
fruits = ["apple", "orange", "banana", "peach"]
last_fruit = fruits.pop()  # takes the last element
print(last_fruit)
 
# output: "peach"
 
second_fruit = fruits.pop(1)  # takes the second element ( = index 1)
print(second_fruit)
 
# output: "orange"
 
print(fruits)  # only fruits that have not been "popped"
               # are still in the list
 
# output: ["apple", "banana"]
list.clear()
decimals = [0.1, 0.2, 0.3, 0.4, 0.5]
decimals.clear()  # remove all values!
print(decimals) 
 
# output: []
list.count()
grades = [7.8, 10.0, 7.9, 9.5, 10.0, 6.5, 9.8, 10.0]
n = grades.count(10.0)
print(n)
 
# output: 3
list.index()
Note: it only returns the index of the first occurrence of a list item.
friends = ["John", "James", "Jessica", "Jack"]
position = friends.index("Jessica")
print(position)
 
# output: 2
list.sort() and list.reverse()
values = [10, 4, -2, 1, 5]
 
values.reverse()
print(values)  # list is reversed
 
# output: [5, 1, -2, 4, 10]
 
values.sort()
print(values)  # list is sorted
 
# output: [-2, 1, 4, 5, 10]
values = [10, 4, -2, 1, 5]
 
values.sort(reverse=True)
print(values)  # list is sorted in reverse order
 
# output: [10, 5, 4, 1, -2]
list.copy()
values_01 = [1, 2, 3, 4]
values_02 = values_01  # not an actual copy: same list object!
 
values_02.append(5)  # we modify the "values_02" list...
print(values_01)     # ... but changes appear also in "values_01"
                     #     because they reference the same list!
 
# output: [1, 2, 3, 4, 5]


values_01 = [1, 2, 3, 4]
values_02 = values_01.copy()  # create an independent copy!
 
values_02.append(5)  # we modify the "values_02" list...
print(values_01)     # ... and changes DO NOT appear in "values_01"
                     #     because it is a copy!
 
# output: [1, 2, 3, 4]

sorted/max/min functions

  • sorted() 無法用在不同 data type
  • sorted() 不會更動變數原始內容
time_list = [12, 2, 32, 19, 57, 22, 14]
print(sorted(time_list))
print(time_list)

time_list = [12, 2, 32, 19, 57, 22, 14]
print(min(time_list))
print(max(time_list))

Extracting from a list

# A element from a list
username_list = ["elarson", "fgarcia", "tshah", "sgilmore"]
print(username_list[2])

# one-liner
print(["elarson", "fgarcia", "tshah", "sgilmore"][2])

# A slice from a list
username_list = ["elarson", "fgarcia", "tshah", "sgilmore"]
print(username_list[0:2])

List with Loop

animals = ["Lion", "Zebra", "Dolphin", "Monkey"]
chars = 0
for animal in animals:
  chars += len(animal)

print("Total characters: {}, Average length: {}".format(chars, chars/len(animals)))

# Output: Total characters: 22, Average length: 5.5

enumerate() 函式會為清單中的每個元素回傳一個 tuple(元組)。元組中的第一個值是該元素在序列中的索引。元組中的第二個值是序列中的元素

winners = ["Ashley", "Dylan", "Reese"]
for index, person in enumerate(winners):
  print("{} - {}".format(index + 1, person))

# Output: 
#1 - Ashley
#2 - Dylan
#3 - Reese

Output by line + 2 "\n"

IDs = ["001","002","003","004"]
print("\n\n".join([id for id in IDs]))

For + If

mylist = [1, 4, 7, 8, 20]

newlist = [x for x in mylist if x % 2 == 0]
print(newlist)

Range()

mylist = ["a", "b", "c", "d", "e", "f", "g"]

for x in range(2, len(mylist) - 1):
    print(mylist[x])

其他類型

Dictionary

  • 符號用大括號
  • key:value 格式
{ 1: "East",

  2: "West",

  3: "North",

  4: "South" }

Set

  • 符號用大括號
  • 內容必須是唯一值,不可重複
{"jlanksy", "drosas", "nmason"}

Cheat Sheet

python_list.jpg

python_list_2.jpg

python_list_methods.jpg

python_data_structure.jpg