您的位置:首页 > 编程语言 > Python开发

Python处理list中的重复元素(重命名,统计,删除等)

2017-11-22 02:47 1526 查看
假设我们有一个python的list:

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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: