Python 101

Common Python Containers

Syntax and Usage

Lists

Ordered, mutable collection of items

indexing

thisList = ['apple', 'samsung', 'LG', 'Google', 'asus']

print(thisList[-1]) # asus
print(thisList[1:4]) # samsung, LG, Google

print(thisList[2:]) # 印出 LG 及其以後的
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
  print("Yes, 'apple' is in the fruits list")

add items

thisList = ['apple', 'samsung', 'LG', 'Google']

thisList.append('acer')
print(thisList) # ['apple', 'samsung', 'LG', 'Google', 'acer']

thisList.insert(1, 'asus')
print(thisList) # 把 asus 插入,使其index為1

remove items

thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
thislist.remove("banana")
print(thislist) # ['apple', 'cherry', 'banana', 'kiwi']

remove 會移除掉"第一項"值為"banana"的項目

thislist.pop(1)

pop 移掉指定index的項目 (若未指定則為末項)

thisList.clear() # 清空 list 的所有元素
del thisList[0]
del thisList # delete the list completely

list comprehension

newlist = [expression for item in iterable if condition == True]

透過這個語法,我們可以快速建立新的 List

newlist = [x for x in fruits if x != "apple"]
newlist = [x**2 for x in nums if x%2 != 0 ]

飯粒如上

sort & join

thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist) # 由小排到大
thislist.sort(reverse = True)
print(thislist) # 由大排到小

Sort

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list1.extend(list2)
print(list1)
# ['a', 'b', 'c', 1, 2, 3]

join

Tuples

Immutable collection of items

  • 元素的值不可更新
  • 幾乎不會用到,但附個用法

Features

Sets

Unordered collection of unique items

  • 元素的值不可更新
  • 無序

Features

Dictionaries

Key-value pairs for efficient data retrieval

  • 成對
  • 可更新

Features

Object-Oriented Programming

Inheritance and Duck Typing

Classes

Blueprint for creating objects with attributes and methods

Inheritance

Allows a class to inherit attributes and methods from another class

Duck Typing

Focuses on what an object can do, rather than its type

Bold

By 賴昱錡

Bold

  • 109