3-1-3-28. Zip and Enumerate
can be pretty helpful.
It’s actually really easy to combine and split lists like this.
If we originally started,
with these two separate lists, items and weights,
and wanted to combine them to create a list,
like manifest, we can use a built-in function called zip.
Zip, returns an iterator.
So, we need to convert it to a list to see the elements.
Or, iterate through it with a for loop,
if we want to print the values, similar to range.
You could also unpack each tuple in a for loop like this.
In addition to zipping two lists together,
you can also unzip a list using an asterisk.
For example, using the manifest lists like this,
you can separate it into an items and weights list, like this.
The next function we’ll look at, is enumerate.
Many times, you’ll find it useful to iterate through the values of a list,
along with the index.
This is one way you could do it.
This uses a for loop to iterate through a list of tuples containing the index,
and value of each item in the list.
The indices are created by getting a range object from zero,
to the length of items minus one,
and zipping that with the values in items.
Enumerate, is a special built-in function that makes this a lot simpler.
Enumerate returns these tuples,
containing the indices and values of a list,
in an iterable for you.
You’ll be getting some practice using Zip and Enumerate and see how helpful they can be,
in the following quiz section.
화물 목록을 다시 살펴보면,
각 요소는 크기가 2인 튜플입니다.
여러 값을 가진 목록을 반복하고,
꽤 도움이 될 수 있습니다.
이와 같이 목록을 결합하고 분할하는 것은 실제로 매우 쉽습니다.
우리가 원래 시작했다면,
이 두 개의 개별 목록, 항목 및 가중치를 사용하여
그것들을 결합하여 목록을 만들고 싶었습니다.
매니페스트와 마찬가지로 zip이라는 내장 함수를 사용할 수 있습니다.
Zip, 반복자를 반환합니다.
따라서 요소를 보려면 목록으로 변환해야 합니다.
또는 for 루프를 사용하여 반복합니다.
범위와 유사한 값을 인쇄하려는 경우.
이와 같이 for 루프에서 각 튜플의 압축을 풀 수도 있습니다.
두 개의 목록을 함께 압축하는 것 외에도
별표를 사용하여 목록의 압축을 풀 수도 있습니다.
예를 들어 다음과 같은 매니페스트 목록을 사용하면
이와 같이 항목과 가중치 목록으로 분리할 수 있습니다.
다음으로 살펴볼 기능은 열거입니다.
여러 번 목록의 값을 반복하는 것이 유용하다는 것을 알게 될 것입니다.
인덱스와 함께.
이것이 당신이 할 수 있는 한 가지 방법입니다.
이것은 for 루프를 사용하여 인덱스를 포함하는 튜플 목록을 반복합니다.
목록에 있는 각 항목의 값.
인덱스는 0에서 범위 객체를 가져와 생성됩니다.
항목의 길이에서 1을 뺀 값,
항목의 값으로 압축합니다.
열거는 이것을 훨씬 더 간단하게 만드는 특별한 내장 함수입니다.
열거형은 이러한 튜플을 반환합니다.
목록의 인덱스와 값을 포함하는
당신을 위해 iterable에서.
Zip 및 Enumerate를 사용하여 연습을 하고 얼마나 도움이 되는지 확인할 수 있습니다.
다음 퀴즈 섹션에서.
Zip and Enumerate
zip
and enumerate
are useful built-in functions that can come in handy when dealing with loops.
Zip
zip
returns an iterator that combines multiple iterables into one sequence of tuples. Each tuple contains the elements in that position from all the iterables. For example, printing
list(zip(['a', 'b', 'c'], [1, 2, 3]))
would output [('a', 1), ('b', 2), ('c', 3)]
.
Like we did for range()
we need to convert it to a list or iterate through it with a loop to see the elements.
You could unpack each tuple in a for
loop like this.
letters = ['a', 'b', 'c'] nums = [1, 2, 3] for letter, num in zip(letters, nums): print("{}: {}".format(letter, num))
In addition to zipping two lists together, you can also unzip a list into tuples using an asterisk.
some_list = [('a', 1), ('b', 2), ('c', 3)] letters, nums = zip(*some_list)
This would create the same letters
and nums
tuples we saw earlier.
Enumerate
enumerate
is a built in function that returns an iterator of tuples containing indices and values of a list. You’ll often use this when you want the index along with each element of an iterable in a loop.
letters = ['a', 'b', 'c', 'd', 'e'] for i, letter in enumerate(letters): print(i, letter)
This code would output:
0 a 1 b 2 c 3 d 4 e
댓글을 달려면 로그인해야 합니다.