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.3. Returning an Element of a List If It Exists


Credit: Nestor Nissen, A. Bass


Problem


You have a list
L and an index
i, and you want to get
L[i] when i is a valid
index into L; otherwise, you want to get a
default value v. If
L were a dictionary,
you'd use L.get(i, v), but lists
don't have a get
method.


Solution


Clearly, we need to code a function, and, in this case, the simplest
and most direct approach is the best one:

def list_get(L, i, v=None):
if -len(L) <= i < len(L): return L[i]
else: return v


Discussion


The function in this recipe just checks whether
i is a valid index by applying
Python's indexing rule: valid indices are negative
ones down to -len(L) inclusive, and non-negative
ones up to len(L) exclusive. If almost all calls
to list_get pass a valid index value for
i, you might prefer an alternative
approach:

def list_get_egfp(L, i, v=None):
try: return L[i]
except IndexError: return v

However, unless a vast majority of the calls pass a valid index, this
alternative (as some time-measurements show) can be up to four times
slower than the list_get function shown in the
solution. Therefore, this "easier to get forgiveness
than permission" (EGFP) approach, although it is
often preferable in Python, cannot be recommended for this specific
case.

I've also tried quite a few fancy, intricate and
obscure approaches, but, besides being hard to explain and to
understand, they all end up slower than the plain, simple function
list_get. General principle: when you write Python
code, prefer clarity and readability to compactness and
tersenesschoose simplicity over subtlety. You often will be
rewarded with code that runs faster, and invariably, you will end up
with code that is less prone to bugs and is easier to maintain, which
is far more important than minor speed differences in 99.9% of the
cases you encounter in the real world.


See Also


Language Reference and Python in a
Nutshell
documentation on list indexing.


/ 394