Python处理list中的重复元素(重命名,统计,删除等)
2017-11-22 02:47
1526 查看
假设我们有一个python的list:
我们希望可以对重复元素进行重命名,统计,删除等操作
1)统计重复元素并保存相应的index:
2)清除重复数据:
3)重命名重复元素
以下为实现代码:
运行结果为:
注: 如果仅想统计list中所有元素出现的次数,可以使用Counter()
origin_list=['JS','Java','JS','Ruby','C++', 'Ruby','Python','Ruby','Python','JS']
我们希望可以对重复元素进行重命名,统计,删除等操作
1)统计重复元素并保存相应的index:
duplicate_dict={'JS': [0,2,9], 'Ruby': [3,5,7], 'Python': [6,8]}
2)清除重复数据:
no_duplicate_list=['JS','Java','Ruby','C++','Python']
3)重命名重复元素
renamed_list=['JS1','Java','JS2','Ruby1','C++', 'Ruby2','Python1','Ruby3','Python2','JS3']`
以下为实现代码:
def rename_duplicate(list, print_result=False): new_list=[v + str(list[:i].count(v) + 1) if list.count(v) > 1 else v for i, v in enumerate(list)] if print_result: print("Renamed list:",new_list) return new_list def clean_duplicate(list,print_result=False): no_duplicate_list=[] duplicate_list=[] duplicate_dict={} for ele in list: duplicate_list.append(ele) if ele not in no_duplicate_list: no_duplicate_list.append(ele) else: ind=len(duplicate_list)-1 duplicate_dict[ele]=duplicate_dict.get(ele,[list.index(ele)]) duplicate_dict[ele].append(ind) if print_result: print('Origin list:',duplicate_list,'\nNew list:',no_duplicate_list,'\nDuplocate dict:',duplicate_dict) return duplicate_list,no_duplicate_list,duplicate_dict origin_list=['JS','Java','JS','Ruby','C++','Ruby','Python','Ruby','Python','JS'] _,no_duplicate_list,duplicate_dict=clean_duplicate(origin_list,True) renamed_list=rename_duplicate(origin_list,True)
运行结果为:
注: 如果仅想统计list中所有元素出现的次数,可以使用Counter()
相关文章推荐
- Python代码实现删除一个list里面的重复元素
- **请写出一段Python代码实现删除一个list里面的重复元素
- 【Python】简单例题tuple和list的转换;实现删除一个list里重复的元素;对list a进行排序,并且从最后一个开始删除重复元素
- python统计list重复的元素
- 面试题---请写出一段Python代码实现删除一个list里面的重复元素
- Python 删除list里面的重复元素
- 【Python进阶】删除list里的重复元素的三种方法效率分析
- Python代码实现:删除一个list里面的重复元素
- 2.7 请写出一段Python代码实现删除一个list里面的重复元素
- python中统计列表list中的不重复元素及其相应个数
- python--删除list中重复的元素
- python 删除list中重复元素
- Python 列表 list 数据类型创建list、添加元素和删除元素
- Python基础篇之List五.(删除元素)
- python list删除元素时要注意的坑点分享
- 删除有序链表的重复元素 Remove Duplicates from Sorted List
- python list删除元素是要注意的坑点
- java中删除list重复元素
- leetcode83---Remove Duplicates from Sorted List(删除重复元素)
- python 统计list中各个元素出现的次数