thiruvenkadam
thiruvenkadam

Reputation: 4250

Create a list from a tuple of tuples

I am looking for a different way to get a string list from a tuple of tuples. This is how I do right now:

x = (('a',1), (2,3), (4,), (), (None,))
op_list = []
for item in x:
    if item and item[0]:
        op_list.append(str(item[0]))
print op_list

Output: ['a', '2', '4']

I cannot think of any other way to get to the list. My question is, is there any better/alternate/pretty way of doing this?

EDIT: Added a few pitfall inputs to the input, like an empty tuple, tuple with None and given the expected output as well. Also edited the question to ensure that I need only a list of strings irrespective of any other data type other than None.

Upvotes: 4

Views: 216

Answers (3)

Inbar Rose
Inbar Rose

Reputation: 43447

Use itemgetter.

from operator import itemgetter
f = itemgetter(0)

def func(i):
    if not i:
        return None
    r = f(i)
    if r:
        return str(r)

Using it:

>>> x = (('a',1), (2,3), (4,), None, '', False, [], (None,), ())
>>> filter(None, map(func, x))
['a', '2', '4']

You can make it into a function:

def extract_first_non_none(collection):
    return filter(None, map(func, collection))

Or into a class:

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))

Using the class:

>>> x = (('a',1), (2,3), (4,), None, '', False, [], (None,), ())
>>> e = Extractor(0)
>>> e.extract(x)
['a', '2', '4']

Upvotes: 1

jabaldonedo
jabaldonedo

Reputation: 26572

Maybe using map and lambda functions gives you the easiest and more compact way to do it:

>>> x = (('a',1), (2,3), (4,), (None,), ())
>>> filter(None, map(lambda i: str(i[0]) if len(i) > 0 and i[0] != None else None, x))
['a', '2', '4']

Upvotes: 2

jamylak
jamylak

Reputation: 133554

>>> x = (('a',1), (2,3), (4,))
>>> [str(item[0]) for item in x if item and item[0]]
['a', '2', '4']

Upvotes: 3

Related Questions