Pythonでのzip()とenumerate()の使用



Usage Zip Enumerate Python



During this time, I reviewed the basic grammar of python and found two very useful functions **zip()** and **enumerate()**, and record their simple usage. #Enter text

zip()とenumerate()は便利な組み込み関数であり、通常はループを処理するときに使用されます。

zip()

zip returns an iterator that combines multiple iterable objects into a sequence of tuples. Each tuple contains the element at that position in all iterable objects. For example, list(zip(['a','b','c'], [1, 2, 3])) will output [('a', 1), ('b', 2), ('c ', 3)]. Just like range(), we need to convert it to a list or use a loop to traverse to see the elements. You can split each tuple with a for loop as shown below. letters = ['a', 'b', 'c'] nums = [1, 2, 3] for letter, num in zip(letters, nums): print('{}: {}'.format(letter, num))

出力



a: 1 b: 2 c: 3 If the length of the parameters passed by the two objects is not equal, the returned list length is equal to the object with the shortest parameter length letters = ['a','b','c','d','e'] nums = [1,2,3] for letter,num in zip(letters,nums): print('{}: {}'.format(letter,num))

出力結果は上記のコードの結果と同じです

In addition to combining two lists together, zip can also use an asterisk (*) to separate them combine_list = [('a', 1), ('b', 2), ('c', 3)] letters, nums = zip(*combine_list)

列挙()

enumerate is a built-in function that returns iterators of tuples containing the index and value of the list. When you need to get each element and index of an iterable object in a loop, you will often use this function. letters = ['a', 'b', 'c', 'd', 'e'] for i, letter in enumerate(letters): print(i, letter)

このコードは出力されます



0 a 1 b 2 c 3 d 4 e