Advertisement
MrPolywhirl

SO-29141609: Which data structure to use in python

Mar 19th, 2015
468
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. def is_number(s):
  2.     try:
  3.         float(s) # for int, long and float
  4.     except ValueError:
  5.         try:
  6.             complex(s) # for complex
  7.         except ValueError:
  8.             return False
  9.     return True
  10.  
  11. data = '''Some Class|Type 10|Type 11
  12. Class 1|0.971|0.968
  13. Class 2|0.995|0.996
  14. Class 3|0.970|0.971
  15. Class 4|0.969|0.970
  16. Class 5|0.992|0.998
  17. Class 6|0.992|0.998
  18. Class 7|0.980|0.984
  19. Class 8|0.973|0.981
  20. Class 9|0.969|0.978
  21. Class 10|0.992|0.998'''
  22.  
  23. rows = data.split('\n')
  24. fields = rows[0].split('|')[1:]
  25. objs = []
  26.  
  27. for row in rows[1:]:
  28.     obj = {}
  29.     for i, col in enumerate(row.split('|')[1:]):
  30.         obj[fields[i]] = float(col) if is_number(col) else col
  31.     objs.append(obj)
  32.        
  33. for i, obj in enumerate(objs):
  34.     print '#{}: {}'.format(i, obj)
  35.  
  36. ''' Output -----------------------------
  37.  
  38. #0: {'Type 10': 0.971, 'Type 11': 0.968}
  39. #1: {'Type 10': 0.995, 'Type 11': 0.996}
  40. #2: {'Type 10': 0.970, 'Type 11': 0.971}
  41. #3: {'Type 10': 0.969, 'Type 11': 0.970}
  42. #4: {'Type 10': 0.992, 'Type 11': 0.998}
  43. #5: {'Type 10': 0.992, 'Type 11': 0.998}
  44. #6: {'Type 10': 0.980, 'Type 11': 0.984}
  45. #7: {'Type 10': 0.973, 'Type 11': 0.981}
  46. #8: {'Type 10': 0.969, 'Type 11': 0.978}
  47. #9: {'Type 10': 0.992, 'Type 11': 0.998}
  48.  
  49. ------------------------------------ '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement