简体   繁体   English

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

[英]Group one list of string elements based on another list

I want to group by my_list based on another list keys as follows: 我想根据另一个列表键对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):

???

The expected answer is: 预期的答案是:

answer = [['apple_2010', 'banana_2010', 'carrot_2010'],
 ['dog_2011', 'eye_2011', 'fig_2011']]
>>> 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']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据另一个列表中的连续元素对一个列表中的项目进行分组? - How to group items in one list based on consecutive elements in another list? 根据另一个列表的元素更改一个列表中的元素 - Change elements in one list based on elements of another list 如何修改基于另一个列表的元素 - How to modify the elements of one list based on another 当一个列表的所有元素都在另一个列表中时,如何分组和求和 - How to group by and sum when all elements of one list are in another list 根据python中的另一个列表匹配列表的元素,其中一个列表的元素是另一个列表的子字符串 - match element of a list based on another list in python where elements of one list is the substring of elements of another list 根据另一个布尔列表从一个列表中获取元素 - Get elements from one list based on another boolean list 根据另一个列表中的索引汇总一个列表中的元素 - Summing up elements from one list based on indices in another list 基于另一个列表中的元素重复一个列表中的元素 - Repeat elements in one list based on elements from another 将一个列表的每个字符串元素连接到另一个列表的所有元素 - Concatenate each string element of one list to all elements of another list 根据另一个列表的元素添加一个列表的元素 - Add elements of a list based on the elements of another list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM