Python 字符串与列表去重

最近面试中出现频率比较高的字符串和列表的去重
pstr = 'abcadcf'
# 字符串去重
# 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、循环遍历法
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)

猜你喜欢

转载自www.cnblogs.com/xyf9575/p/11094387.html