根据另一个列表组合一个字符串元素列表

时间:2014-12-07 05:36:06

标签: python

我想基于另一个列表键按my_list分组,如下所示:

my_list = ['apple_2010', 'banana_2010', 'carrot_2010', 'dog_2011', 'eye_2011', 'fig_2011']

keys = ['2010','2010','2010','2011','2011','2011']

for x,y in zip(my_list,keys):

???

预期的答案是:

answer = [['apple_2010', 'banana_2010', 'carrot_2010'],
 ['dog_2011', 'eye_2011', 'fig_2011']]

1 个答案:

答案 0 :(得分:4)

>>> my_list = ['apple_2010', 'banana_2010', 'carrot_2010', 'dog_2011', 'eye_2011', 'fig_2011']
>>> keys = ['2010','2010','2010','2011','2011','2011']
>>> print [[value for value in my_list if key in value] for key in set(keys)]

[['dog_2011', 'eye_2011', 'fig_2011'], ['apple_2010', 'banana_2010', 'carrot_2010']]