在平時(shí)的工作中,處理重復(fù)數(shù)據(jù)不可避免掩浙,在大數(shù)據(jù)時(shí)代更是有著海量的數(shù)據(jù)花吟,如果不對數(shù)據(jù)進(jìn)行去重,會嚴(yán)重影響分析效率厨姚。因而衅澈,我們在進(jìn)行大數(shù)據(jù)分析時(shí)的第一步就是檢測和消除其中的重復(fù)數(shù)據(jù),通過數(shù)據(jù)去重谬墙,一方面可以減少存儲的空間和網(wǎng)絡(luò)帶寬的占用今布;另一方面可以減少數(shù)據(jù)的分析量。在工作中拭抬,遇到最多的就是字符串和列表的去重部默,下面介紹幾種字符串的去重方法:
1.通過for循環(huán)遍歷字符串去重
str='abcdefaaffegecdh'
new_str=''
for i in str:
if i not in new_str: #如果不在結(jié)果字符串中
new_str += i #添加到結(jié)果字符串的末尾
print (new_str)
output:
abcdefgh
2.通過while循環(huán)遍歷字符串去重
str='abcdefaaffegecdh'
new_str=''
i = len(str)-1 #獲取字符串的長度-1,即最大索引值
while True:
if i >=0: #如果還超出索引范圍
if str[i] not in new_str:
new_str += (str[i])
i-=1
else: #超出索引范圍則結(jié)束循環(huán)
break
print (new_str)
output:
hdcegfab
3.使用列表的方法去重
str='abcdefaaffegecdh'
str1=set(str) #轉(zhuǎn)換為集合玖喘,則去除重復(fù)元素
print(str1)
new_str = list(set(str)) #將集合轉(zhuǎn)換為列表
print('_'.join(new_str)) #將列表連接為字符串并輸出
new_str.sort(key=str.index) #對列表排序
print(new_str)
print(''.join(new_str)) #將排序后的列表連接為字符串并輸出
output:
{'e', 'b', 'g', 'f', 'a', 'h', 'c', 'd'}
e_b_g_f_a_h_c_d
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
abcdefgh
4.在原字符串中直接刪除
str='abcdefaaffegecdh'
len = len(str) # 字符串下標(biāo)總長度
for s in str:
if str[0] in str[1:len]:
str = str[1:len]
else:
str= str[1:len]+str[0]
print(str)
output:
bafgecdh
5.使用fromkeys()方法把字符串轉(zhuǎn)換成字典
str='abcdefaaffegecdh'
dict={}.fromkeys(str)
mylist=list(dict.keys())
mylist = list({}.fromkeys(str).keys())
print(mylist)
print ('_'.join(mylist))
output:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a_b_c_d_e_f_g_h
參考資料:《python編程錦囊》明日科技甩牺。