Pin-Jiun / Python

Python Document
0 stars 0 forks source link

29-zip and enumerate #29

Open Pin-Jiun opened 1 year ago

Pin-Jiun commented 1 year ago

zip

zip函數可以把多個list的相對應位置鏈起來,zip可以將多個迭代器相對應位置打包成元組(Tuple),返回一個可迭代物件zip object。

如果要使用此zip object, 使用方式為list(zipped_data)

friends = ["a","b","c","d"]
height = [169,172,173,175]
seat_num = [1,2,3,4]

zipped_data = zip(friends, height, seat_num)

print(zipped_data)
#<zip object at 0x000001DCF84014C0>
print(list(zipped_data))
#[('a', 169, 1), ('b', 172, 2), ('c', 173, 3), ('d', 175, 4)]

注意如果要串起來的列表長度不一樣的話,會以短的列表為主,忽略長列表多出來的資料

然而,有時候我們並不事先知道我們有幾個參數,而是資料都存在一個列表中,這時我們便可以用python中的星號「*」來解決這個問題,範例如下:

friends = ["a","b","c","d"]
height = [169,172,173,175]
seat_num = [1,2,3,4]

zipped_data = zip(friends, height, seat_num)
data = list(zipped_data)
#[('a', 169, 1), ('b', 172, 2), ('c', 173, 3), ('d', 175, 4)]
zipped_data = zip(*data)

print(list(zipped_data))
#[('a', 'b', 'c', 'd'), (169, 172, 173, 175), (1, 2, 3, 4)]

zip處理二維列表(或稱矩陣)的操作

假設要對選擇題答案


answer = ['A', 'B', 'B', 'E', 'D', 'C']
my_input = ['B', 'B', 'B', 'E', 'A', 'C']

def check(answer, wenwen):
    n = 0
    for i in range(len(answer)):
        if answer[i]!= wenwen[i]:
            n += 1
    return n

print(check(answer, my_input))

可以使用zip更簡化

answer = ['A', 'B', 'B', 'E', 'D', 'C']
my_input = ['B', 'B', 'B', 'E', 'A', 'C']

def check(answer, wenwen):
    wrong_num = 0
    for x, y in zip(answer, wenwen):
        if x != y:
            wrong_num +=1

    return wrong_num

print(check(answer, my_input))

list(zipped(*A))這個操作可以將A的行、列元素互換。zip的結果預設會打包成元組(tuple)

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(list((zip(*a))))
#[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

字典鍵(key)、值(value)互換

D = {'s':"黑桃", 'h':"紅心", 'd':"方塊", 'c':"梅花"}
print(dict(zip(D.values(), D.keys())))

#{'黑桃': 's', '紅心': 'h', '方塊': 'd', '梅花': 'c'}

https://ithelp.ithome.com.tw/articles/10218029

Pin-Jiun commented 1 year ago

使用 enumerate() 函式來同時輸出索引與元素

https://clay-atlas.com/blog/2019/11/08/python-chinese-function-enumerate/

enumerate(iterable, start_index)。 前者輸入一個可迭代的對象、比如說 List 資料型態;後者輸入開始的起點編號,為數字,若不設定時從 0 開始。

List = ['a', 'b', 'c', 'd', 'e']

for value in enumerate(List):
    print(value)

也可以在 for 迴圈當中分開 index 以及 value:

for index, value in enumerate(List):
    print(index, value)