The map() function
Let's do some mapping!
Do you remember how zip() works? It merges given Iterables so that items with the same index fall into the same tuple. Moreover, the output is restricted by the shortest Iterable.
Your task is to define your own my_zip() function with *args depicting a variable number of Iterables, e.g. lists, strings, tuples etc. Rather than a zip object, my_zip() should already return a list of tuples.
Comment: args should be checked whether they contain Iterables first. But we omit it for simplicity.
本练习是课程的一部分
Practicing Coding Interview Questions in Python
练习说明
- Retrieve Iterable
lengthsfromargsusingmap()and find the minimal length. - Within the loop, create the
mappingusingmap()to retrieve the elements inargswith the same indexi. - Convert the mapping to a tuple and append it to the
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)