diff list by set part 2
จากที่เมื่อวานใช้ set มาช่วยในการ diff list แล้วปรากฏว่ามันจะมีปัญหากับสมาชิกของ list ที่เป็น dict เลยจัดการแปลงสมาชิกทุกตัวให้เป็น string representative ก่อน แล้วค่อยแปลงกลับด้วย eval (ใช้ร่วมกับ list comprehensions เพื่อทำให้ code กระชับ)
def list_diff(list_a, list_b):
set_a = set([item.__repr__() for item in list_a])
set_b = set([item.__repr__() for item in list_b])
set_int = set_a.intersection(set_b)
return {'---':[eval(item) for item in list(set_a - set_int)],
'===':[eval(item) for item in list(set_int)],
'+++':[eval(item) for item in list(set_b - set_int)]}
เมื่อใช้งานจริงจะได้ดังนี้
In [2]: a = [{'x':123},'Hello World', 789]
In [3]: b = ['Hello World', 456, {'y':567}]
In [4]: list_diff(a,b)
Out[4]: {'+++': [{'y': 567}, 456], '---': [{'x': 123}, 789], '===': ['Hello World']}
Tar: เป็นความรู้ที่ดีมากครับ จอติดตามต่อไปเรื่อยๆนะครับ...
1 comment(s) 26/2/2009 22:19
