Python 字符串与列表去重
作者:互联网
字符串去重
1、使用集合 --没有保持原来的顺序
print(set(pstr))
2、使用字典 -- 没有保持原来的顺序
print({}.fromkeys(pstr).keys())
3、使用循环遍历法 -- 代码不够简洁,不高端
a = []
for i in range(len(pstr)):
if pstr[i] not in a:
a.append(pstr[i])
print(a)
列表去重
plist = [1,0,3,7,5,7]
1、使用set方法
print(list(set(plist)))
2、使用字典
print(list({}.fromkeys(plist).keys()))
3、循环遍历法
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
plist1 = []
for i in plist:
if i not in plist1:
plist1.append(i)
print(plist1)
4、按照索引再次排序
b = list(set(plist))
b.sort(key=plist.index)
print('sds:',b)
标签:pstr,set,Python,列表,print,字符串,--,plist,plist1 来源: https://blog.51cto.com/u_14246112/2797510