Create a list from a tuple of tuples

I am looking for another way to get a list of strings from a tuple of tuples. Here's how I do it 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 can't think of another way to get to the list. My question is, is there a better / alternative / great way to do this?

EDIT: added several input signals for input, for example, an empty tuple, a tuple with None and giving the expected result. A question has also been edited to make sure that I only need a list of strings, regardless of the data type other than None.

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

Perhaps using map and lambda functions give you the easiest and most compact way to do this:

 >>> 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'] 
+2
source

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 do this in a function:

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

Or to the 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)) 

Class usage:

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

Source: https://habr.com/ru/post/1488263/


All Articles