python组通过字符串匹配模式列出项目

时间:2019-08-23 02:09:00

标签: python string list

我需要将类似的项目分组:

['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'] ...]

席卷了整个互联网,但找不到任何有关字符串操作的信息。应该是简单的fnmatch或字符串匹配,但我无法正常工作。

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

2 个答案:

答案 0 :(得分:3)

您需要使用相同的键对列表进行排序:

[list(g) for k, g in groupby(sorted(lst, key=f), key=f)]

其中f是:

f = lambda x: x.split('_')[1:]

示例

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']]

答案 1 :(得分:0)

由于排序,您建议的解决方案为 O(nlogn) O(n)解决方案仅是使用collections.defaultdict

from collections import defaultdict

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']

d = defaultdict(list)
for string in lst:
    _, key = string.split("_", 1)
    d[key].append(string)

print(list(d.values()))

输出:

[['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']]