使用itemgetter
.
from operator import itemgetter
f = itemgetter(0)
def func(i):
if not i:
return None
r = f(i)
if r:
return str(r)
使用它:
>>> x = (('a',1), (2,3), (4,), None, '', False, [], (None,), ())
>>> filter(None, map(func, x))
['a', '2', '4']
你可以把它变成一个函数:
def extract_first_non_none(collection):
return filter(None, map(func, collection))
或者进入一个类:
class Extractor():
def __init__(self, index):
self.getter = itemgetter(index)
def _func(self, item):
if not item:
return None
r = self.getter(item)
if r != None:
return str(r)
def extract(self, collection):
return filter(None, map(self._func, collection))
使用类:
>>> x = (('a',1), (2,3), (4,), None, '', False, [], (None,), ())
>>> e = Extractor(0)
>>> e.extract(x)
['a', '2', '4']