Friday, 15 April 2011

Combine Python List Elements Based On Another List -



Combine Python List Elements Based On Another List -

i have 2 lists:

phon = ["a","r","k","h"] idx = [1,2,3,3]

idx corresponds how phon should grouped. in case, phon_grouped should ["a","r","kh"] because both "k" , "h" correspond grouping 3.

i'm assuming sort of zip or map function required, i'm not sure how implement it. have like:

a = [] in enumerate(phon): a[idx[i-1].append(phon[i])

but not work/compile

use zip() , itertools.groupby() grouping output after zipping:

from itertools import groupby operator import itemgetter result = [''.join([c i, c in group]) key, grouping in groupby(zip(idx, phon), itemgetter(0))]

itertools.groupby() requires input sorted on key (your idx values here).

zip() pairs indices idx characters phon itertools.groupby() groups resulting tuples on first value, index. equal index values puts tuples same group the list comprehension picks characters grouping 1 time again , joins them strings.

demo:

>>> itertools import groupby >>> operator import itemgetter >>> phon = ["a","r","k","h"] >>> idx = [1,2,3,3] >>> [''.join([c i, c in group]) key, grouping in groupby(zip(idx, phon), itemgetter(0))] ['a', 'r', 'kh']

python list

No comments:

Post a Comment