0
点赞
收藏
分享

微信扫一扫

python列表去重方法

hwwjian 2023-04-14 阅读 52

#!/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 条评论