utils_list.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import random
  2. def to_list(obj):
  3. if obj is None:
  4. return None
  5. elif hasattr(obj, '__iter__') and not isinstance(obj, str):
  6. try:
  7. return list(obj)
  8. except:
  9. return [obj]
  10. else:
  11. return [obj]
  12. def convert_lists_to_record(*list_objs, delimiter=None):
  13. assert len(list_objs) >= 1, 'list_objs length must >= 1.'
  14. delimiter = delimiter or ','
  15. assert isinstance(list_objs[0], (tuple, list))
  16. number = len(list_objs[0])
  17. for item in list_objs[1:]:
  18. assert isinstance(item, (tuple, list))
  19. assert len(item) == number, '{} != {}'.format(len(item), number)
  20. records = []
  21. record_list = zip(*list_objs)
  22. for record in record_list:
  23. record_str = [str(item) for item in record]
  24. records.append(delimiter.join(record_str))
  25. return records
  26. def shuffle_table(*table):
  27. """
  28. Notes:
  29. table can be seen as list of list which have equal items.
  30. """
  31. shuffled_list = list(zip(*table))
  32. random.shuffle(shuffled_list)
  33. tuple_list = zip(*shuffled_list)
  34. return [list(item) for item in tuple_list]
  35. def transpose_table(table):
  36. """
  37. Notes:
  38. table can be seen as list of list which have equal items.
  39. """
  40. m, n = len(table), len(table[0])
  41. return [[table[i][j] for i in range(m)] for j in range(n)]