[英]How to get common elements together in a python list?
This might sound like a stupid question but I have the following list:这听起来像是一个愚蠢的问题,但我有以下列表:
list = ['a','b','c','d','a','b','c','d']
And I want to get common elements together to rearrange it as:我想把共同的元素放在一起,把它重新排列为:
sorted_list = ['a','a','b','b','c','c','d','d']
Is there any built in function in python to do that? python中是否有任何内置函数可以做到这一点?
Well to get sorted list you could just use:要获得排序列表,您可以使用:
sorted_list = sorted(list)
which gives the output ['a','a','b','b','c','c','d','d']
这给出了输出['a','a','b','b','c','c','d','d']
To sort and group elements by values:要按值对元素进行排序和分组:
list = sorted(list)
sorted_list = [[y for y in list if y==x] for x in list]
which gives the output [['a','a'],['b','b'],['c','c'],['d','d']]
这给出了输出[['a','a'],['b','b'],['c','c'],['d','d']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.