Python 中有許多 function 接收的 arguments 是 iterable objects,因此就來好好瞭解一下 Python iterable object 吧!
Python 中的 Iterable Objects 如下:
- str
- list
- tuple
- dict
- set
Table of Contents
1. 定義
可以被 for loop iterate (迭代) 的,就會是 iterable objects
my_str = 'hi'
for i in my_str:
print(i)
h
i
my_list = [1, 2]
for i in my_list:
print(i)
1
2
my_tuple = (1, 2)
for i in my_tuple:
print(i)
1
2
my_dict = { 'name': 'jimmy', 'city': 'taipei' }
for i in my_dict:
print(i)
name
city
my_set = {1, 2}
for i in my_set:
print(i)
1
2
2. argument 接收 Iterable Objects 的 Buillt-in types
2.1 list
可將 iterable object 轉換成 list。
class list([iterable])
my_str = 'hi'
print(list(my_str))
['h', 'i']
my_tuple = (1, 2)
print(list(my_tuple))
[1, 2]
my_dict = { 'name': 'jimmy', 'city': 'taipei' }
print(list(my_dict))
['name', 'city']
print(list(my_dict.values()))
['jimmy', 'taipei']
my_set = {1, 2}
print(list(my_set))
[1, 2]
2.2 tuple
可將 iterable object 轉換成 tuple。
class tuple([iterable])
my_str = 'hi'
print(tuple(my_str))
('h', 'i')
my_list = [1, 2]
print(tuple(my_list))
(1, 2)
my_dict = { 'name': 'jimmy', 'city': 'taipei' }
print(tuple(my_dict))
('name', 'city')
print(tuple(my_dict.values()))
('jimmy', 'taipei')
my_set = {1, 2}
print(tuple(my_set))
(1, 2)
2.3 dict
dict 接收的 iterable object argument 需要滿足一些條件:
- 在 iterable object 中的每個 item 必須也是 iterable object,且該 object 必須正好有兩個 objects
- 第一個 object 會作為 dict 的 key,第二個 object 則作為 value
class dict(**kwargs) class dict(mapping, **kwargs) class dict(iterable, **kwargs)
my_info = [('name', 'Jimmy'), ('city', 'Taipei')]
print(dict(my_info))
{'name': 'Jimmy', 'city': 'Taipei'}
my_dict = { 'name': 'jimmy', 'city': 'taipei' }
print(dict(my_dict))
{'name': 'Jimmy', 'city': 'Taipei'}
# set 不保證順序,因此用來 init dict 的時候,key 和 value 的順序可能不同
my_set = [{'name', 'Jimmy'}, {'city', 'Taipei'}]
print(dict(my_set))
{'Jimmy': 'name', 'city': 'Taipei'}
my_data = ({'name', 'Jimmy'}, {'city', 'Taipei'})
print(dict(my_data))
{'Jimmy': 'name', 'city': 'Taipei'}
2.4 set
可將 iterable object 轉換成 set,但 iterable object 的每個 item 都必須是 hashable object,否則無法轉成 set:
An object is hashable if it has a hash value which never changes during its lifetime (it needs a__hash__()
method), and can be compared to other objects (it needs an__eq__()
method). 資料來源:Python document
class set([iterable])
my_str = 'hi'
print(set(my_str))
{'h', 'i'}
my_list = [1, 2]
print(set(my_list))
{1, 2}
my_tuple = (1, 2)
print(set(my_tuple))
{1, 2}
# set 不保證順序
my_dict = { 'name': 'jimmy', 'city': 'taipei' }
print(set(my_dict))
{'city', 'name'}
print(set(my_dict.values()))
{'taipei', 'jimmy'}
my_set = {1, 2}
print(set(my_set))
{1, 2}
my_list = [[1], [2]]
print(set(my_list))
TypeError: unhashable type: 'list'
3. argument 接收 Iterable Objects 的 Built-in Functions
3.1 sum
sum 會將 iterable object 的所有 items 做相加,但這些 items 只能是 bool (True 或 False) 和 Numeric Type,否則會噴錯。其中,True 會當成 1,False 則會當成 0。
sum(iterable, /, start=0)
my_str = 'hi'
print(sum(my_str))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
my_dict = { 'name': 'jimmy', 'city': 'taipei' }
print(sum(my_dict))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
my_bool = [True, False]
print(sum(my_bool))
1
my_bool = [10, False]
print(sum(my_bool))
10
my_bool = [True, 10]
print(sum(my_bool))
11
my_list = [1, 2]
print(sum(my_list))
3
my_tuple = (1, 2)
print(sum(my_tuple))
3
my_set = {1, 2}
print(sum(my_set))
3
3.2 sorted
會 new 一個 list object,並將 iterable object 做排序後,塞到 list 裡面回傳。
有三個 arguments:
- iterable – iterable object
- reverse – 是否要將 list 的順序反轉
- key – optional argument,可以是個 value 或是 function
sorted(iterable, /, *, reverse=False, key=None)
my_str = 'hi'
print(sorted(my_str))
['h', 'i']
my_list = [3, 5, 1, 2, 4]
print(sorted(my_list))
[1, 2, 3, 4, 5]
my_tuple = (3, 5, 1, 2, 4)
print(sorted(my_tuple))
[1, 2, 3, 4, 5]
my_dict = { 'name': 'jimmy', 'city': 'taipei' }
print(sorted(my_dict))
['city', 'name']
print(sorted(my_dict.values()))
['jimmy', 'taipei']
my_set = {3, 5, 1, 2, 4}
print(sorted(my_set))
[1, 2, 3, 4, 5]
reverse argument
my_list = [3, 5, 1, 2, 4]
print(sorted(my_list))
[1, 2, 3, 4, 5]
my_list = [3, 5, 1, 2, 4]
print(sorted(my_list, reverse=True))
[5, 4, 3, 2, 1]
key argument
# 將 item 的長度做排序
programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"]
print(sorted(programming_languages, key=len))
['Go', 'C++', 'Java', 'Rust', 'Swift', 'Python']
# 按照 item 的某個 value 做排序
programming_languages = [
{'language':'Python','year':1991},
{'language':'Swift','year':2014},
{'language':'Java', 'year':1995},
{'language':'C++','year':1985},
{'language':'Go','year':2007},
{'language':'Rust','year':2010}
]
def get_year(element):
return element['year']
print(sorted(programming_languages, key=get_year))
# or
print(sorted(programming_languages, key=lambda element: element['year']))
[
{'language': 'C++', 'year': 1985},
{'language': 'Python', 'year': 1991},
{'language': 'Java', 'year': 1995},
{'language': 'Go', 'year': 2007},
{'language': 'Rust', 'year': 2010},
{'language': 'Swift', 'year': 2014}
]
3.3 any
如果 iterable object 中的任一 item 是 True 的話,回傳 True,否則回傳 False。
如果 iterable object 裡面沒有任何 item,也會回傳 False。
any(iterable)
my_str = 'hi'
print(any(my_str))
True
my_list = []
print(any(my_list))
False
my_list = [0, None, [], 'hi']
print(any(my_list))
True
my_tuple = (0, None, [], '')
print(any(my_tuple))
False
3.4 all
跟 any 相反,iterable object 的所有 items 都要是 True 才會回傳 True,否則回傳 False。
如果 iterable object 裡面沒有任何 item,則會回傳 True。
all(iterable)
my_str = 'hi'
print(all(my_str))
True
my_list = []
print(all(my_list))
True
my_list = [0, None, [], 'hi']
print(all(my_tuple))
False
my_tuple = (0, None, [], '')
print(all(my_tuple))
False
3.5 max
max 可以用來回傳 iterable object 中最大的 item,其中 key argument 和 sorted 中的 key 一樣,可以用來指定比較的基準。
如果傳入 max 的 iterable object 可能是空的,則需要給一個 default argument,用來指定當 iterable object 沒有任何 item 的話,max 要回傳什麼 value
max(iterable, *, key=None) max(iterable, *, default, key=None) max(arg1, arg2, *args, key=None)
my_set = {3, 5, 1, 2, 4}
print(max(my_set))
5
print(max([], default='Hello'))
Hello
print(max([]))
ValueError: max() arg is an empty sequence
programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"]
print(max(programming_languages, key=len))
Python
programming_languages = [
{'language':'Python','year':1991},
{'language':'Swift','year':2014},
{'language':'Java', 'year':1995},
{'language':'C++','year':1985},
{'language':'Go','year':2007},
{'language':'Rust','year':2010}
]
print(max(programming_languages, key= lambda element: element['year']))
{'language': 'Swift', 'year': 2014}
3.6 min
min 和 max 類似,只是會回傳 iterable object 中最小的 item
min(iterable, *, key=None) min(iterable, *, default, key=None) min(arg1, arg2, *args, key=None)
my_set = {3, 5, 1, 2, 4}
print(min(my_set))
1
print(min([], default='Hello'))
Hello
print(min([]))
ValueError: min() arg is an empty sequence
programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"]
print(min(programming_languages, key=len))
Go
programming_languages = [
{'language':'Python','year':1991},
{'language':'Swift','year':2014},
{'language':'Java', 'year':1995},
{'language':'C++','year':1985},
{'language':'Go','year':2007},
{'language':'Rust','year':2010}
]
print(min(programming_languages, key= lambda element: element['year']))
{'language': 'C++', 'year': 1985}
3.7 enumerate
enumerate 接收一個 iterable object 作為 augument,並且會回傳 enumerate object,enumerate object 其實就像個 iterable object 一樣,而這個 iterable object 的每個 item 都是一個 tuple,其中這個 tuple 又由 index 和 value 組成。
enumerate(iterable, start=0)
programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"]
my_enumerate = enumerate(programming_languages)
print(my_enumerate)
<enumerate object at 0x1051955d0>
print(type(my_enumerate))
<class 'enumerate'>
# iterable object 可以用 for loop 取得 items
for enumerate_item in my_enumerate:
print(enumerate_item)
(0, 'Python')
(1, 'Swift')
(2, 'Java')
(3, 'C++')
(4, 'Go')
(5, 'Rust')
第二個 argument 則是可以指定 index 要從多少開始算,不給的話 default value 是 0:
programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"]
my_enumerate = enumerate(programming_languages, 5)
for enumerate_item in my_enumerate:
print(enumerate_item)
(5, 'Python')
(6, 'Swift')
(7, 'Java')
(8, 'C++')
(9, 'Go')
(10, 'Rust')
常見的用法:與 list 搭配使用:
my_str = 'hi'
print(list(enumerate(my_str)))
[(0, 'h'), (1, 'i')]
my_list = [1, 2]
print(list(enumerate(my_list)))
[(0, 1), (1, 2)]
my_tuple = (1, 2)
print(list(enumerate(my_tuple)))
[(0, 1), (1, 2)]
my_dict = { 'name': 'jimmy', 'city': 'taipei' }
print(list(enumerate(my_dict)))
[(0, 'name'), (1, 'city')]
my_set = {1, 2}
print(list(enumerate(my_set)))
[(0, 1), (1, 2)]
參考資料
Iterables – Python Like You Mean It
Python Iterators
Built-in Functions — Python 3.11.4 documentation
Built-in Types — Python 3.11.4 documentation
Python .sort() – How to Sort a List in Python – freeCodeCamp
如果覺得我的文章有幫助的話,歡迎幫我的粉專按讚哦~謝謝你!