Guest User

Untitled

a guest
Jun 18th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. d = [('A', 'B', 1), ('C', 'D', 1),
  2. ('B', 'D', 2), ('A', 'B', 3),
  3. ('A', 'D', 3), ('B', 'C', 4),
  4. ('A', 'C', 5), ('B', 'C', 8)]
  5.  
  6. d = [('A', 'B', 1), ('C', 'D', 1),
  7. ('B', 'D', 2), ('A', 'D', 3),
  8. ('B', 'C', 4), ('A', 'C', 5)]
  9.  
  10. edge_dict = {}
  11.  
  12. for x in d:
  13. key = '%s%s' % (x[0], x[1])
  14. if not edge_dict.get(key):
  15. edge_dict[key] = x[2]
  16. else:
  17. if edge_dict[key] > x[2]:
  18. edge_dict[key] = x[2]
  19.  
  20. final_list = []
  21. for k, v in edge_dict.items():
  22. t = list(k)
  23. t.append(v)
  24. final_list.append(tuple(t))
  25.  
  26.  
  27. final_list.sort(key=lambda x: x[2])
  28. print final_list
  29.  
  30. import itertools
  31. d = [('A', 'B', 1), ('C', 'D', 1),
  32. ('B', 'D', 2), ('A', 'B', 3),
  33. ('A', 'D', 3), ('B', 'C', 4),
  34. ('A', 'C', 5), ('B', 'C', 8)]
  35. new_d = [min(list(b), key=lambda x:x[-1]) for _, b in itertools.groupby(sorted(d, key=lambda x:x[:-1]), key=lambda x:x[:-1])]
  36.  
  37. [('A', 'B', 1), ('A', 'C', 5), ('A', 'D', 3), ('B', 'C', 4), ('B', 'D', 2), ('C', 'D', 1)]
Add Comment
Please, Sign In to add comment