Debian Codegraph @

DisplayCAL/util_list.py

raw
1 """Utility functions for list conversion, indexing, and natural sorting."""
2
3 import re
4
5
6 def floatlist(alist):
7 """Convert all list items to floats (0.0 on error)."""
8 result = []
9 for item in alist:
10 try:
11 result.append(float(item))
12 except ValueError:
13 result.append(0.0)
14 return result
15
16
17 def get(alist, index, default=None):
18 """Similar to dict.get, return item at index or default if not in list."""
19 if -1 < index < len(alist):
20 return alist[index]
21 return default
22
23
24 def index_ignorecase(self, value, start=None, stop=None):
25 """Case-insensitive version of list.index."""
26 items = [(item.lower() if isinstance(item, str) else item) for item in self]
27 return items.index(value, start or 0, stop or len(self))
28
29
30 def index_fallback_ignorecase(self, value, start=None, stop=None):
31 """Return index of value in list. Prefer a case-sensitive match."""
32 if value in self:
33 return self.index(value, start or 0, stop or len(self))
34 return index_ignorecase(self, value, start or 0, stop or len(self))
35
36
37 def intlist(alist):
38 """Convert all list items to ints (0 on error)."""
39 result = []
40 for item in alist:
41 try:
42 result.append(int(item))
43 except ValueError:
44 result.append(0)
45 return result
46
47
48 alphanumeric_re = re.compile(r"\D+|\d+")
49
50
51 def natsort_key_factory(ignorecase=True, n=10):
52 """Create natural sort key function.
53
54 Note that if integer parts are longer than n digits, sort order may no
55 longer be entirely natural.
56
57 """
58
59 def natsort_key(item):
60 matches = alphanumeric_re.findall(item)
61 key = []
62 for match in matches:
63 if match.isdigit():
64 match = match.rjust(n, "0")
65 elif ignorecase:
66 match = match.lower()
67 key.append(match)
68 return key
69
70 return natsort_key
71
72
73 def natsort(list_in, ignorecase=True, reverse=False, n=10):
74 """Sort a list which (also) contains integers naturally.
75
76 Note that if integer parts are longer than n digits, sort order will no
77 longer be entirely natural.
78
79 """
80 return sorted(list_in, key=natsort_key_factory(ignorecase, n), reverse=reverse)
81
82
83 def strlist(alist):
84 """Convert all list items to strings."""
85 return [str(item) for item in alist]