開始使用免費開始

map() 函式

來做點 mapping 吧!

還記得 zip() 怎麼運作嗎?它會把多個 Iterable 合併,讓相同索引的位置落在同一個 tuple 裡。而且輸出會受最短的 Iterable 限制。

你的任務是定義自己的 my_zip() 函式,使用 *args 來表示可變數量的 Iterable,例如 list、string、tuple 等等。my_zip() 應該回傳的是由 tuple 組成的 list,而不是 zip 物件。

備註:嚴格來說應該先檢查 args 是否包含 Iterable,但這裡為了簡化先省略。

本練習屬於課程

Python 程式面試題實作練習

檢視課程

練習說明

  • 使用 map()args 取出各 Iterable 的 lengths,並找出最小長度。
  • 在迴圈中,使用 map() 建立 mapping,取出 args 中索引 i 相同的元素。
  • 將 mapping 轉成 tuple,並附加到 tuple_list

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

def my_zip(*args):
    
    # Retrieve Iterable lengths and find the minimal length
    lengths = list(map(____, ____))
    min_length = ____

    tuple_list = []
    for i in range(0, min_length):
        # Map the elements in args with the same index i
        mapping = map(____, args)
        # Convert the mapping and append it to tuple_list
        tuple_list.append(____(____))

    return tuple_list

result = my_zip([1, 2, 3], ['a', 'b', 'c', 'd'], 'DataCamp')
print(result)
編輯並執行程式碼