Python Cookbook 2Nd Edition Jun 1002005 [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Python Cookbook 2Nd Edition Jun 1002005 [Electronic resources] - نسخه متنی

David Ascher, Alex Martelli, Anna Ravenscroft

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید







Recipe 4.4. Looping over Items and Their Indices in a Sequence


Credit: Alex Martelli, Sami Hangaslammi


Problem


You need to loop on a sequence, but at
each step you also need to know which index into the sequence you
have reached (e.g., because you need to rebind some entries in the
sequence), and Python's preferred approach to
looping doesn't use the indices.


Solution


That's what built-in function
enumerate is for. For example:

for index, item in enumerate(sequence):
if item > 23:
sequence[index] = transform(item)

This is cleaner, more readable, and faster than the alternative of
looping over indices and accessing items by indexing:

for index in range(len(sequence)):
if sequence[index] > 23:
sequence[index] = transform(sequence[index])


Discussion


Looping on a sequence is a very frequent need, and Python strongly
encourages you to do just that, looping on the sequence directly. In
other words, the Pythonic way to get each item in a sequence is to
use:

for item in sequence:
process(item)

rather than the indirect approach, typical of lower-level languages,
of looping over the sequence's indices and using
each index to fetch the corresponding item:

for index in range(len(sequence)):
process(sequence[index])

Looping directly is cleaner, more readable, faster, and more general
(since you can loop on any iterable, by definition, while indexing
works only on sequences, such as lists).

However, sometimes you do need to know the index, as well as the
corresponding item, within the loop. The most frequent reason for
this need is that, in order to rebind an entry in a list, you must
assign the new item to thelist[index]. To support
this need, Python offers the built-in function
enumerate, which takes any iterable argument and
returns an iterator yielding all the pairs (two-item tuples) of the
form (index,
item), one pair at a time. By writing your
for loop's header clause in the
form:

for index, item in enumerate(sequence):

both the index and the item are available within the
loop's body.

For help remembering the order of the items in each pair
enumerate yields, think of the idiom
d=dict(enumerate(L)).
This gives a dictionary d
that's equivalent to list
L, in the sense that d[i] is
L[i]
for any valid non-negative index
i.


See Also


Library Reference and Python in a
Nutshell
section about enumerate;
Chapter 19.


/ 394