python列表去重方法

奋斗吧
奋斗吧
擅长邻域:未填写

标签: python列表去重方法 博客 51CTO博客

2023-04-14 18:23:59 242浏览

python列表去重方法,#!/usr/bin/python3withopen("d:/pythoncode/duplicate_content.txt","r")asf:content=f.readlines()f.close()print(len(content))#foriinrange(len(content)):#forjinrange(len(con
#!/usr/bin/python3

with open("d:/pythoncode/duplicate_content.txt","r") as f:
    content=f.readlines()
    f.close()
print(len(content))

# for i in range(len(content)):
#     for j in range(len(content)-i,len(content)):
#         print(i,j)
#         if content[i]==content[j]:
#             print(content[j])
#             del content[j]

# print(content)

####for循环去重##########################################################

temp = []
for i in content:
    if not i in temp:
        temp.append(i)
print("for循环去重:",len(temp))

########################################################################


#####列表推导式去重######################################################
temp = []
[temp.append(i) for i in content if i not in temp]
print("列表推导式去重:",len(temp))


########################################################################



#####set去重#############################################################
temp = list(set(content))
print("set去重:",len(temp))


########################################################################


#####使用字典fromkeys()的方法来去重#######################################
temp = {}.fromkeys(content).keys()
print("使用字典fromkeys()的方法来去重:",len(temp))
# print(list(temp))

##################################################################



#####使用sort + set去重(保持原来的顺序#######################################
list2 = list(set(content))
list2.sort(key=content.index)
print("使用sort + set去重,保持顺序:",len(list2))


##################################################################



#####使用sorted+ set函数去重#######################################

temp = sorted(set(content), key=content.index)
print("使用sorted+ set函数去重:",len(temp))


##################################################################

好博客就要一起分享哦!分享海报

此处可发布评论

评论(0展开评论

暂无评论,快来写一下吧

展开评论

您可能感兴趣的博客

客服QQ 1913284695