I need to group similar items like this:
['bty_char_rick_10', 'shd_char_rick_10', 'refl_char_rick_10', 'spec_char_rick_10'], ['bty_char_toby_01', 'shd_char_toby_01'], ['bty_prop_item_01', 'shd_prop_item_01'] ...]
been sweeping the whole internet but can't find anything regarding string operations. should be a simple fnmatch or string match but I can't get it to work.
from itertools import groupby
lst = ['bty_char_rick_10', 'bty_char_toby_01', 'bty_prop_chair_20', 'bty_prop_item_01', 'bty_prop_vase_10', 'bty_vhcl_tessla_10', 'occ_prop_vase_10', 'refl_char_rick_10', 'refl_prop_vase_10', 'shd_char_rick_10', 'shd_char_toby_01', 'shd_prop_chair_20', 'shd_prop_item_01', 'shd_prop_vase_10', 'shd_vhcl_tessla_10', 'spec_char_rick_10']
keyf = lambda text: text.split('_')[1]+'_'+text.split('_')[2]
print [list(items) for gr, items in groupby(sorted(lst), key=keyf)]
You need to sort the list by the same key:
[list(g) for k, g in groupby(sorted(lst, key=f), key=f)]
where f is:
f = lambda x: x.split('_')[1:]
Example:
from itertools import groupby
lst = ['bty_char_rick_10', 'bty_char_toby_01', 'bty_prop_chair_20', 'bty_prop_item_01',
'bty_prop_vase_10', 'bty_vhcl_tessla_10', 'occ_prop_vase_10', 'refl_char_rick_10',
'refl_prop_vase_10', 'shd_char_rick_10', 'shd_char_toby_01', 'shd_prop_chair_20',
'shd_prop_item_01', 'shd_prop_vase_10', 'shd_vhcl_tessla_10', 'spec_char_rick_10']
f = lambda x: x.split('_')[1:]
print([list(g) for k, g in groupby(sorted(lst, key=f), key=f)])
# [['bty_char_rick_10', 'refl_char_rick_10', 'shd_char_rick_10', 'spec_char_rick_10'],
# ['bty_char_toby_01', 'shd_char_toby_01'],
# ['bty_prop_chair_20', 'shd_prop_chair_20'],
# ['bty_prop_item_01', 'shd_prop_item_01'],
# ['bty_prop_vase_10', 'occ_prop_vase_10', 'refl_prop_vase_10', 'shd_prop_vase_10'],
# ['bty_vhcl_tessla_10', 'shd_vhcl_tessla_10']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With