不管順序的去重轉為set即可
1.將序列中重復元素去除,并保持順序
#如果序列items中的值是可哈希的
def dedupe(items):
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
?>>> a = [1, 5, 2, 1, 9, 1, 5, 10]
>>> list(dedupe(a))
[1, 5, 2, 9, 10]
寫成函數形式是使程序更通用,如讀文件去除重復行:
with open(somefile,'r') as f:
for line in dedupe(f):
...
# 如果序列items中的值是不可哈希-這個更通用,也支持可哈希序列
def dedupe(items, key=None):
seen = set()
for item in items:
val = item if key is None else key(item)
if val not in seen:
yield item
seen.add(val)
>>> a = [ {'x':1, 'y':2}, {'x':1, 'y':3}, {'x':1, 'y':2}, {'x':2, 'y':4}]
>>> list(dedupe(a, key=lambda d: (d['x'],d['y'])))
[{'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 2, 'y': 4}]
>>> list(dedupe(a, key=lambda d: d['x']))
[{'x': 1, 'y': 2}, {'x': 2, 'y': 4}]
其中,key是一個從不可哈希值轉為可哈希值的函數,并按key()的返回值去重,若值已經可哈希,則令key=None
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
hashable?-- 可哈希
一個對象的哈希值如果在其生命周期內絕不改變,就被稱為?
可哈希
?(它需要具有?
__hash__()
?方法),并可以同其他對象進行比較(它需要具有?
__eq__()
?方法)。可哈希對象必須具有相同的哈希值比較結果才會相同。
可哈希性使得對象能夠作為字典鍵或集合成員使用,因為這些數據結構要在內部使用哈希值。
大多數 Python 中的不可變內置對象都是可哈希的;可變容器(例如列表或字典)都不可哈希;不可變容器(例如元組和 frozenset)僅當它們的元素均為可哈希時才是可哈希的。 用戶定義類的實例對象默認是可哈希的。 它們在比較時一定不相同(除非是與自己比較),它們的哈希值的生成是基于它們的?
id()
。
List
x = [1,2,3]
y = {x: 9}#生成字典y報錯
Traceback (most recent call last):
File "
", line 1, in
TypeError: unhashable type: 'list'
Tuple
z = (5,6)
y = {z: 89}
print(y)
{(5, 6): 89}
?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
yield詳解:
https://pyzh.readthedocs.io/en/latest/the-python-yield-keyword-explained.html
https://www.jianshu.com/p/d09778f4e055
https://blog.csdn.net/dcrmg/article/details/78128041?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
