Python Intro
列表 (List)
使用 join() 方法將列表中的所有元素連接成一個字串。
list = ["this", "is", "an", "example", "of", "using", "join()", "method"]
seperator = " - "
new_list = seperator.join(list)
print(new_list)
# this - is - an - example - of - using - join() - method
使用 split() 方法將字串拆分為列表。
print(new_list.split(seperator))
# ['this', 'is', 'an', 'example', 'of', 'using', 'join()', 'method']
集合 (Set)
intersection() , difference() , union()
set_1 = {1, 2, 3}
set_2 = {2, 3, 4}
print(set_1.intersection(set_2))
print(set_1.difference(set_2))
print(set_2.difference(set_1))
print(set_1.union(set_2))
#{2, 3}
#{1}
#{4}
#{1, 2, 3, 4}
字典 (Dictionary)
索引存取 VS get()
get() 在鍵不存在時會回傳 None,而不是拋出 KeyError。
dict_1 = {
"name": "4pril",
"age": 24,
}
print(dict_1.get("phone") is None)
#True
print(dict_1["phone"])
#Traceback (most recent call last):
# File "C:\Users\Administrator\PyCharmMiscProject\test.py", line 24, in <module>
# print(dict_1["phone"])
# ~~~~~~^^^^^^^^^
#KeyError: 'phone'
keys() , values() , items()
print(dict_1.keys())
#dict_keys(['name', 'age'])
print(dict_1.values())
#dict_values(['4pril', 24])
print(dict_1.items())
#dict_items([('name', '4pril'), ('age', 24)])
for k, v in dict_1.items():
print(k, v, sep=" - ")
#name - 4pril
#age - 24
format()
name = '4pril'
print("name is {}".format(name))
# name is 4pril
* 和 **
def func(*args, **kwargs):
print(args)
print(kwargs)
func(1,2,3, name = '4pril', age = 24)
print('--------------------------------------')
func([1,2,3], {'name': '4pril', 'age': 24})
print('--------------------------------------')
func(*[1,2,3], **{'name': '4pril', 'age': 24})
print('--------------------------------------')
#(1, 2, 3)
#{'name': '4pril', 'age': 24}
#--------------------------------------
#([1, 2, 3], {'name': '4pril', 'age': 24})
#{}
#--------------------------------------
#(1, 2, 3)
#{'name': '4pril', 'age': 24}
#--------------------------------------
Comprehensions
List Comprehension
1 | nums = [1, 2, 3, 4] |
Set Comprehension
1 | nums = [1, 2, 3, 4, 5, 1, 3] |
Dictionary Comprehension
1 | name = ['Tom', 'Bob', 'Andy'] |
Generator Comprehension
1 | list = [1, 2, 3, 4, 5] |
There is a yield in square function, which means it is a generator function. when it is called, it returns a generator object .
During the for loop where calling the square function, Python actually executes logic similar to this:
1 | g = square(list) |
next() is a build-in function that retrieves the next value produced by a generator.
The first time next(g) is called, the generator runs until it reaches yield, returning 1.
The function then pauses at that position.
The next time next(g) is called, execution resumes from where it paused, so the variable num continues from 2 instead of starting again from 1.
sorted()
Preparation for data structure
1 | class Student: |
There are several ways to use sorted() function.
Using a normal function as the key.
Using lambda expression to specify the key.
Using the
attrgetter()built-in function to retrieve the attribute used for sorting.
1 | def get_name(student) |
Generator
generator is an essential feature of Python. Anyone who wants to become familiar with Python should understand how they work.
Why is generator so important ? Let’s look at the example below.
1 | '''Suppose we want to get the squeare of every number in a list, |
In this case, all values are computed at once. If there are 10,000,000 number in the list and having such large amount of values in memory would be low-efficient and redundant.
To improve efficiency, we can use a generator.
1 | def square(list): |
When using a generator, values are produced one at a time only when they are requested, instead of computing all values in advance.
The generator can also be iterated using a for loop:
1 | for num in square_numbers: |
Additionally, we can also create a generator by using parentheses.
1 | nums = (n * n for n in [1, 2, 3, 4, 5]) |
Now let’s look at the difference in memory usage and execution time between a list and a generator.
1 | import sys |









