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、循环遍历法
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)
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论