Extract first item of each sublist in Python
Using list comprehension: >>> lst = [[‘a’,’b’,’c’], [1,2,3], [‘x’,’y’,’z’]] >>> lst2 = [item[0] for item in lst] >>> lst2 [‘a’, 1, ‘x’]
Using list comprehension: >>> lst = [[‘a’,’b’,’c’], [1,2,3], [‘x’,’y’,’z’]] >>> lst2 = [item[0] for item in lst] >>> lst2 [‘a’, 1, ‘x’]
If you want multiple matches, this works: greeting = [‘hello’,’my’,’name’,’is’,’bob’,’how’,’are’,’you’,’my’,’name’,’is’] def find_sub_list(sl,l): results=[] sll=len(sl) for ind in (i for i,e in enumerate(l) if e==sl[0]): if l[ind:ind+sll]==sl: results.append((ind,ind+sll-1)) return results print find_sub_list([‘my’,’name’,’is’], greeting) # [(1, 3), (8, 10)] Or if you just want the first match: greeting = [‘hello’,’my’,’name’,’is’,’bob’,’how’,’are’,’you’,’my’,’name’,’is’] def find_sub_list(sl,l): sll=len(sl) for ind in (i … Read more
>>> [list(x[1]) for x in itertools.groupby([‘|’, u’MOM’, u’DAD’, ‘|’, u’GRAND’, ‘|’, u’MOM’, u’MAX’, u’JULES’, ‘|’], lambda x: x==’|’) if not x[0]] [[u’MOM’, u’DAD’], [u’GRAND’], [u’MOM’, u’MAX’, u’JULES’]]