query
stringlengths 9
60
| language
stringclasses 1
value | code
stringlengths 105
25.7k
| url
stringlengths 91
217
|
---|---|---|---|
sort string list | python | def sort_string_by_pairs(strings):
"""Group a list of strings by pairs, by matching those with only
one character difference between each other together."""
assert len(strings) % 2 == 0
pairs = []
strings = list(strings) # This shallow copies the list
while strings:
template = strings.pop()
for i, candidate in enumerate(strings):
if count_string_diff(template, candidate) == 1:
pair = [template, strings.pop(i)]
pair.sort()
pairs.append(pair)
break
return pairs | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L120-L134 |
sort string list | python | def sort_list(items):
"""Sort a simple list by number of words and length."""
# Track by number of words.
track = {}
def by_length(word1, word2):
return len(word2) - len(word1)
# Loop through each item.
for item in items:
# Count the words.
cword = utils.word_count(item, all=True)
if cword not in track:
track[cword] = []
track[cword].append(item)
# Sort them.
output = []
for count in sorted(track.keys(), reverse=True):
sort = sorted(track[count], key=len, reverse=True)
output.extend(sort)
return output | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/sorting.py#L120-L143 |
sort string list | python | def file_sort(my_list):
"""
Sort a list of files in a nice way.
eg item-10 will be after item-9
"""
def alphanum_key(key):
"""
Split the key into str/int parts
"""
return [int(s) if s.isdigit() else s for s in re.split("([0-9]+)", key)]
my_list.sort(key=alphanum_key)
return my_list | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/autodoc.py#L118-L131 |
sort string list | python | def sort_strings(strings, sort_order=None, reverse=False, case_sensitive=False, sort_order_first=True):
"""Sort a list of strings according to the provided sorted list of string prefixes
TODO:
- Provide an option to use `.startswith()` rather than a fixed prefix length (will be much slower)
Arguments:
sort_order_first (bool): Whether strings in sort_order should always preceed "unknown" strings
sort_order (sequence of str): Desired ordering as a list of prefixes to the strings
If sort_order strings have varying length, the max length will determine the prefix length compared
reverse (bool): whether to reverse the sort orded. Passed through to `sorted(strings, reverse=reverse)`
case_senstive (bool): Whether to sort in lexographic rather than alphabetic order
and whether the prefixes in sort_order are checked in a case-sensitive way
Examples:
>>> sort_strings(['morn32', 'morning', 'unknown', 'date', 'dow', 'doy', 'moy'],
... ('dat', 'dow', 'moy', 'dom', 'doy', 'mor'))
['date', 'dow', 'moy', 'doy', 'morn32', 'morning', 'unknown']
>>> sort_strings(['morn32', 'morning', 'unknown', 'less unknown', 'lucy', 'date', 'dow', 'doy', 'moy'],
... ('dat', 'dow', 'moy', 'dom', 'doy', 'mor'), reverse=True)
['unknown', 'lucy', 'less unknown', 'morning', 'morn32', 'doy', 'moy', 'dow', 'date']
Strings whose prefixes don't exist in `sort_order` sequence can be interleaved into the
sorted list in lexical order by setting `sort_order_first=False`
>>> sort_strings(['morn32', 'morning', 'unknown', 'lucy', 'less unknown', 'date', 'dow', 'doy', 'moy'],
... ('dat', 'dow', 'moy', 'dom', 'moy', 'mor'),
... sort_order_first=False) # doctest: +NORMALIZE_WHITESPACE
['date', 'dow', 'doy', 'less unknown', 'lucy', 'moy', 'morn32', 'morning', 'unknown']
"""
if not case_sensitive:
sort_order = tuple(s.lower() for s in sort_order)
strings = tuple(s.lower() for s in strings)
prefix_len = max(len(s) for s in sort_order)
def compare(a, b, prefix_len=prefix_len):
if prefix_len:
if a[:prefix_len] in sort_order:
if b[:prefix_len] in sort_order:
comparison = sort_order.index(a[:prefix_len]) - sort_order.index(b[:prefix_len])
comparison = int(comparison / abs(comparison or 1))
if comparison:
return comparison * (-2 * reverse + 1)
elif sort_order_first:
return -1 * (-2 * reverse + 1)
# b may be in sort_order list, so it should be first
elif sort_order_first and b[:prefix_len] in sort_order:
return -2 * reverse + 1
return (-1 * (a < b) + 1 * (a > b)) * (-2 * reverse + 1)
return sorted(strings, key=functools.cmp_to_key(compare)) | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L189-L238 |
sort string list | python | def sort(self, *, key: Optional[Callable[[Any], Any]] = None, reverse: bool = False) -> None:
"""
Sort _WeakList.
:param key: Key by which to sort, default None.
:param reverse: True if return reversed WeakList, false by default.
"""
return list.sort(self, key=self._sort_key(key), reverse=reverse) | https://github.com/PatrikValkovic/grammpy/blob/879ce0ef794ac2823acc19314fcd7a8aba53e50f/grammpy/representation/support/_WeakList.py#L205-L211 |
sort string list | python | def sort(self, order="asc"):
"""Getting the sorted result of the given list
:@param order: "asc"
:@type order: string
:@return self
"""
self.__prepare()
if isinstance(self._json_data, list):
if order == "asc":
self._json_data = sorted(self._json_data)
else:
self._json_data = sorted(self._json_data, reverse=True)
return self | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L429-L444 |
sort string list | python | def _sort(self, short_list, sorts):
"""
TAKE SHORTLIST, RETURN IT SORTED
:param short_list:
:param sorts: LIST OF SORTS TO PERFORM
:return:
"""
sort_values = self._index_columns(sorts)
# RECURSIVE SORTING
output = []
def _sort_more(short_list, i, sorts):
if len(sorts) == 0:
output.extend(short_list)
sort = sorts[0]
index = self._index[sort_values[i]]
if sort.sort == 1:
sorted_keys = sorted(index.keys())
elif sort.sort == -1:
sorted_keys = reversed(sorted(index.keys()))
else:
sorted_keys = list(index.keys())
for k in sorted_keys:
self._sort(index[k] & short_list, i + 1, sorts[1:])
_sort_more(short_list, 0, sorts)
return output | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_python/containers/doc_store.py#L144-L174 |
sort string list | python | def sort(self, key=None, reverse=False):
"""
Sort contents using sort() method available to list()
:return: None (because list().sort() doesn't return anything)
"""
self.log('sort()')
self.contents.sort(key=key, reverse=reverse)
return None | https://github.com/jhazelwo/python-fileasobj/blob/4bdbb575e75da830b88d10d0c1020d787ceba44d/fileasobj/__init__.py#L286-L293 |
sort string list | python | def sort(self, sort_list):
""" Sort """
order = []
for sort in sort_list:
if sort_list[sort] == "asc":
order.append(asc(getattr(self.model, sort, None)))
elif sort_list[sort] == "desc":
order.append(desc(getattr(self.model, sort, None)))
return order | https://github.com/loverajoel/sqlalchemy-elasticquery/blob/4c99b81f59e7bb20eaeedb3adbf5126e62bbc25c/sqlalchemy_elasticquery/elastic_query.py#L159-L167 |
sort string list | python | def sort(self):
"""
Sort the fragments in the list.
:raises ValueError: if there is a fragment which violates
the list constraints
"""
if self.is_guaranteed_sorted:
self.log(u"Already sorted, returning")
return
self.log(u"Sorting...")
self.__fragments = sorted(self.__fragments)
self.log(u"Sorting... done")
self.log(u"Checking relative positions...")
for i in range(len(self) - 1):
current_interval = self[i].interval
next_interval = self[i + 1].interval
if current_interval.relative_position_of(next_interval) not in self.ALLOWED_POSITIONS:
self.log(u"Found overlapping fragments:")
self.log([u" Index %d => %s", i, current_interval])
self.log([u" Index %d => %s", i + 1, next_interval])
self.log_exc(u"The list contains two fragments overlapping in a forbidden way", None, True, ValueError)
self.log(u"Checking relative positions... done")
self.__sorted = True | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L248-L271 |
sort string list | python | def sort_nicely(l):
"""Sort the given list in the way that humans expect."""
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
l.sort(key=alphanum_key) | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/examples/images.py#L22-L26 |
sort string list | python | def human_sorting(the_list):
"""Sort the given list in the way that humans expect.
From http://stackoverflow.com/a/4623518
:param the_list: The list to sort.
:type the_list: list
:return: The new sorted list.
:rtype: list
"""
def try_int(s):
try:
return int(s)
except ValueError:
return s
def alphanum_key(s):
"""Turn a string into a list of string and number chunks.
For instance : "z23a" -> ["z", 23, "a"]
"""
return [try_int(c) for c in re.split('([0-9]+)', s)]
the_list.sort(key=alphanum_key)
return the_list | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/utilities.py#L332-L357 |
sort string list | python | def parse_sort_string(sort):
"""
Parse a sort string for use with elasticsearch
:param: sort: the sort string
"""
if sort is None:
return ['_score']
l = sort.rsplit(',')
sortlist = []
for se in l:
se = se.strip()
order = 'desc' if se[0:1] == '-' else 'asc'
field = se[1:] if se[0:1] in ['-', '+'] else se
field = field.strip()
sortlist.append({field: {"order": order, "unmapped_type": "string", "missing": "_last"}})
sortlist.append('_score')
return sortlist | https://github.com/OnroerendErfgoed/oe_utils/blob/7b2014bda8ac6bb71b7138eaa06ac17ef3ff4a6d/oe_utils/search/__init__.py#L22-L39 |
sort string list | python | def sort(self):
"""
Sort the list based on dependancies.
@return: The sorted items.
@rtype: list
"""
self.sorted = list()
self.pushed = set()
for item in self.unsorted:
popped = []
self.push(item)
while len(self.stack):
try:
top = self.top()
ref = next(top[1])
refd = self.index.get(ref)
if refd is None:
log.debug('"%s" not found, skipped', Repr(ref))
continue
self.push(refd)
except StopIteration:
popped.append(self.pop())
continue
for p in popped:
self.sorted.append(p)
self.unsorted = self.sorted
return self.sorted | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/xsd/deplist.py#L67-L93 |
sort string list | python | def sort(self, *args, **kwargs):
"""Sort this setlist in place."""
self._list.sort(*args, **kwargs)
for index, value in enumerate(self._list):
self._dict[value] = index | https://github.com/mlenzen/collections-extended/blob/ee9e86f6bbef442dbebcb3a5970642c5c969e2cf/collections_extended/setlists.py#L544-L548 |
sort string list | python | def index_list_for_sort_order(x: List[Any], key: Callable[[Any], Any] = None,
reverse: bool = False) -> List[int]:
"""
Returns a list of indexes of ``x``, IF ``x`` WERE TO BE SORTED.
Args:
x: data
key: function to be applied to the data to generate a sort key; this
function is passed as the ``key=`` parameter to :func:`sorted`;
the default is ``itemgetter(1)``
reverse: reverse the sort order?
Returns:
list of integer index values
Example:
.. code-block:: python
z = ["a", "c", "b"]
index_list_for_sort_order(z) # [0, 2, 1]
index_list_for_sort_order(z, reverse=True) # [1, 2, 0]
q = [("a", 9), ("b", 8), ("c", 7)]
index_list_for_sort_order(q, key=itemgetter(1))
"""
def key_with_user_func(idx_val: Tuple[int, Any]):
return key(idx_val[1])
if key:
sort_key = key_with_user_func
# see the simpler version below
else:
sort_key = itemgetter(1)
# enumerate, below, will return tuples of (index, value), so
# itemgetter(1) means sort by the value
index_value_list = sorted(enumerate(x), key=sort_key, reverse=reverse)
return [i for i, _ in index_value_list] | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/lists.py#L48-L84 |
sort string list | python | def alphabetical_sort(list_to_sort: Iterable[str]) -> List[str]:
"""Sorts a list of strings alphabetically.
For example: ['a1', 'A11', 'A2', 'a22', 'a3']
To sort a list in place, don't call this method, which makes a copy. Instead, do this:
my_list.sort(key=norm_fold)
:param list_to_sort: the list being sorted
:return: the sorted list
"""
return sorted(list_to_sort, key=norm_fold) | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/utils.py#L211-L223 |
sort string list | python | def sort(self):
"""Sort list elements by ID."""
super(JSSObjectList, self).sort(key=lambda k: k.id) | https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jssobjectlist.py#L143-L145 |
sort string list | python | def sort(self, ascending=True):
"""
Sort all values in this SArray.
Sort only works for sarray of type str, int and float, otherwise TypeError
will be raised. Creates a new, sorted SArray.
Parameters
----------
ascending: boolean, optional
If true, the sarray values are sorted in ascending order, otherwise,
descending order.
Returns
-------
out: SArray
Examples
--------
>>> sa = SArray([3,2,1])
>>> sa.sort()
dtype: int
Rows: 3
[1, 2, 3]
"""
from .sframe import SFrame as _SFrame
if self.dtype not in (int, float, str, datetime.datetime):
raise TypeError("Only sarray with type (int, float, str, datetime.datetime) can be sorted")
sf = _SFrame()
sf['a'] = self
return sf.sort('a', ascending)['a'] | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L3495-L3526 |
sort string list | python | def sort_and_distribute(array, splits=2):
""" Sort an array of strings to groups by alphabetically continuous
distribution
"""
if not isinstance(array, (list,tuple)): raise TypeError("array must be a list")
if not isinstance(splits, int): raise TypeError("splits must be an integer")
remaining = sorted(array)
if sys.version_info < (3, 0):
myrange = xrange(splits)
else:
myrange = range(splits)
groups = [[] for i in myrange]
while len(remaining) > 0:
for i in myrange:
if len(remaining) > 0: groups[i].append(remaining.pop(0))
return groups | https://github.com/OLC-Bioinformatics/sipprverse/blob/d4f10cdf8e1a39dac0953db61c21c97efc6006de/cgecore/utility.py#L373-L388 |
sort string list | python | def sort_by_name(self):
"""Sort list elements by name."""
super(JSSObjectList, self).sort(key=lambda k: k.name) | https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jssobjectlist.py#L147-L149 |
sort string list | python | def sort_by_list_order(sortlist, reflist, reverse=False, fltr=False,
slemap=None):
"""
Sort a list according to the order of entries in a reference list.
Parameters
----------
sortlist : list
List to be sorted
reflist : list
Reference list defining sorting order
reverse : bool, optional (default False)
Flag indicating whether to sort in reverse order
fltr : bool, optional (default False)
Flag indicating whether to filter `sortlist` to remove any entries
that are not in `reflist`
slemap : function or None, optional (default None)
Function mapping a sortlist entry to the form of an entry in
`reflist`
Returns
-------
sortedlist : list
Sorted (and possibly filtered) version of sortlist
"""
def keyfunc(entry):
if slemap is not None:
rle = slemap(entry)
if rle in reflist:
# Ordering index taken from reflist
return reflist.index(rle)
else:
# Ordering index taken from sortlist, offset
# by the length of reflist so that entries
# that are not in reflist retain their order
# in sortlist
return sortlist.index(entry) + len(reflist)
if fltr:
if slemap:
sortlist = filter(lambda x: slemap(x) in reflist, sortlist)
else:
sortlist = filter(lambda x: x in reflist, sortlist)
return sorted(sortlist, key=keyfunc, reverse=reverse) | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/docs/source/automodule.py#L36-L81 |
sort string list | python | def natsort(l, key=None, reverse=False):
"""
Sort the given list in the way that humans expect (using natural order sorting).
:param l: An iterable of strings to sort.
:param key: An optional sort key similar to the one accepted by Python's
built in :func:`sorted()` function. Expected to produce
strings.
:param reverse: Whether to reverse the resulting sorted list.
:returns: A sorted list of strings.
"""
return sorted(l, key=lambda v: NaturalOrderKey(key and key(v) or v), reverse=reverse) | https://github.com/xolox/python-naturalsort/blob/721c9c892029b2d04d482adfc66088bcc7526ce8/natsort/__init__.py#L22-L33 |
sort string list | python | def _sort_to_str(self):
"""
Before exec query, this method transforms sort dict string
from
{"name": "asc", "timestamp":"desc"}
to
"name asc, timestamp desc"
"""
params_list = []
timestamp = ""
for k, v in self._solr_params['sort'].items():
if k != "timestamp":
params_list.append(" ".join([k, v]))
else:
timestamp = v
params_list.append(" ".join(['timestamp', timestamp]))
self._solr_params['sort'] = ", ".join(params_list) | https://github.com/zetaops/pyoko/blob/236c509ad85640933ac0f89ad8f7ed95f62adf07/pyoko/db/adapter/db_riak.py#L899-L923 |
sort string list | python | def tsort(self):
"""Given a partial ordering, return a totally ordered list.
part is a dict of partial orderings. Each value is a set,
which the key depends on.
The return value is a list of sets, each of which has only
dependencies on items in previous entries in the list.
raise ValueError if ordering is not possible (check for circular or missing dependencies)"""
task_dict = {}
for key, task in self.tasks.iteritems():
task_dict[task] = task.dependencies
# parts = parts.copy()
parts = task_dict.copy()
result = []
while True:
level = set([name for name, deps in parts.iteritems() if not deps])
if not level:
break
result.append(level)
parts = dict([(name, deps - level) for name, deps in parts.iteritems() if name not in level])
if parts:
raise ValueError('total ordering not possible (check for circular or missing dependencies)')
return result | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/tasks.py#L197-L223 |
sort string list | python | def sort(self, cmp=None, key=None, reverse=False):
"""
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
"""
self._col_list.sort(cmp, key, reverse) | https://github.com/fuzeman/PyUPnP/blob/6dea64be299952346a14300ab6cc7dac42736433/pyupnp/lict.py#L262-L267 |
sort string list | python | def sort_filenames(filenames):
"""
sort a list of files by filename only, ignoring the directory names
"""
basenames = [os.path.basename(x) for x in filenames]
indexes = [i[0] for i in sorted(enumerate(basenames), key=lambda x:x[1])]
return [filenames[x] for x in indexes] | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/utils.py#L936-L942 |
sort string list | python | def sort(self):
"""Sorts all results rows.
Sorts by: size (descending), n-gram, count (descending), label,
text name, siglum.
"""
self._matches.sort_values(
by=[constants.SIZE_FIELDNAME, constants.NGRAM_FIELDNAME,
constants.COUNT_FIELDNAME, constants.LABEL_FIELDNAME,
constants.WORK_FIELDNAME, constants.SIGLUM_FIELDNAME],
ascending=[False, True, False, True, True, True], inplace=True) | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/results.py#L989-L1000 |
sort string list | python | def sort(iterable):
"""
Given an IP address list, this function sorts the list.
:type iterable: Iterator
:param iterable: An IP address list.
:rtype: list
:return: The sorted IP address list.
"""
ips = sorted(normalize_ip(ip) for ip in iterable)
return [clean_ip(ip) for ip in ips] | https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/ipv4.py#L276-L286 |
sort string list | python | def argsort(*args, **kwargs):
"""
like np.argsort but for lists
Args:
*args: multiple lists to sort by
**kwargs:
reverse (bool): sort order is descending if True else acscending
CommandLine:
python -m utool.util_list argsort
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> result = ut.argsort({'a': 3, 'b': 2, 'c': 100})
>>> print(result)
"""
if len(args) == 1 and isinstance(args[0], dict):
dict_ = args[0]
index_list = list(dict_.keys())
value_list = list(dict_.values())
return sortedby2(index_list, value_list)
else:
index_list = list(range(len(args[0])))
return sortedby2(index_list, *args, **kwargs) | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1597-L1622 |
sort string list | python | def _sort_text(definition):
""" Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item>
"""
# If its 'hidden', put it next last
prefix = 'z{}' if definition.name.startswith('_') else 'a{}'
return prefix.format(definition.name) | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/plugins/jedi_completion.py#L95-L102 |
sort string list | python | def sortedby(item_list, key_list, reverse=False):
""" sorts ``item_list`` using key_list
Args:
list_ (list): list to sort
key_list (list): list to sort by
reverse (bool): sort order is descending (largest first)
if reverse is True else acscending (smallest first)
Returns:
list : ``list_`` sorted by the values of another ``list``. defaults to
ascending order
SeeAlso:
sortedby2
Examples:
>>> # ENABLE_DOCTEST
>>> import utool
>>> list_ = [1, 2, 3, 4, 5]
>>> key_list = [2, 5, 3, 1, 5]
>>> result = utool.sortedby(list_, key_list, reverse=True)
>>> print(result)
[5, 2, 3, 1, 4]
"""
assert len(item_list) == len(key_list), (
'Expected same len. Got: %r != %r' % (len(item_list), len(key_list)))
sorted_list = [item for (key, item) in
sorted(list(zip(key_list, item_list)), reverse=reverse)]
return sorted_list | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1477-L1507 |
sort string list | python | def sortedby2(item_list, *args, **kwargs):
""" sorts ``item_list`` using key_list
Args:
item_list (list): list to sort
*args: multiple lists to sort by
**kwargs:
reverse (bool): sort order is descending if True else acscending
Returns:
list : ``list_`` sorted by the values of another ``list``. defaults to
ascending order
CommandLine:
python -m utool.util_list --exec-sortedby2 --show
Examples:
>>> # ENABLE_DOCTEST
>>> from utool.util_list import * # NOQA
>>> import utool as ut
>>> item_list = [1, 2, 3, 4, 5]
>>> key_list1 = [1, 1, 2, 3, 4]
>>> key_list2 = [2, 1, 4, 1, 1]
>>> args = (key_list1, key_list2)
>>> kwargs = dict(reverse=False)
>>> result = ut.sortedby2(item_list, *args, **kwargs)
>>> print(result)
[2, 1, 3, 4, 5]
Examples:
>>> # ENABLE_DOCTEST
>>> # Python 3 Compatibility Test
>>> import utool as ut
>>> item_list = [1, 2, 3, 4, 5]
>>> key_list1 = ['a', 'a', 2, 3, 4]
>>> key_list2 = ['b', 'a', 4, 1, 1]
>>> args = (key_list1, key_list2)
>>> kwargs = dict(reverse=False)
>>> result = ut.sortedby2(item_list, *args, **kwargs)
>>> print(result)
[3, 4, 5, 2, 1]
"""
assert all([len(item_list) == len_ for len_ in map(len, args)])
reverse = kwargs.get('reverse', False)
key = operator.itemgetter(*range(1, len(args) + 1))
tup_list = list(zip(item_list, *args))
#print(tup_list)
try:
sorted_tups = sorted(tup_list, key=key, reverse=reverse)
except TypeError:
# Python 3 does not allow sorting mixed types
def keyfunc(tup):
return tuple(map(str, tup[1:]))
sorted_tups = sorted(tup_list, key=keyfunc, reverse=reverse)
sorted_list = [tup[0] for tup in sorted_tups]
return sorted_list | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_list.py#L1510-L1565 |
sort string list | python | def sorted_list_indexes(list_to_sort, key=None, reverse=False):
"""
Sorts a list but returns the order of the index values of the list for the sort and not the values themselves.
For example is the list provided is ['b', 'a', 'c'] then the result will be [2, 1, 3]
:param list_to_sort: list to sort
:param key: if not None then a function of one argument that is used to extract a comparison key from each
list element
:param reverse: if True then the list elements are sorted as if each comparison were reversed.
:return: list of sorted index values
"""
if key is not None:
def key_func(i):
return key(list_to_sort.__getitem__(i))
else:
key_func = list_to_sort.__getitem__
return sorted(range(len(list_to_sort)), key=key_func, reverse=reverse) | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/sort_utils.py#L37-L53 |
sort string list | python | def sort(self, key, *get_patterns,
by=None, offset=None, count=None,
asc=None, alpha=False, store=None):
"""Sort the elements in a list, set or sorted set."""
args = []
if by is not None:
args += [b'BY', by]
if offset is not None and count is not None:
args += [b'LIMIT', offset, count]
if get_patterns:
args += sum(([b'GET', pattern] for pattern in get_patterns), [])
if asc is not None:
args += [asc is True and b'ASC' or b'DESC']
if alpha:
args += [b'ALPHA']
if store is not None:
args += [b'STORE', store]
return self.execute(b'SORT', key, *args) | https://github.com/aio-libs/aioredis/blob/e8c33e39558d4cc91cf70dde490d8b330c97dc2e/aioredis/commands/generic.py#L255-L272 |
sort string list | python | def sort(self, ids):
"""
Sort the given list of identifiers,
returning a new (sorted) list.
:param list ids: the list of identifiers to be sorted
:rtype: list
"""
def extract_int(string):
"""
Extract an integer from the given string.
:param string string: the identifier string
:rtype: int
"""
return int(re.sub(r"[^0-9]", "", string))
tmp = list(ids)
if self.algorithm == IDSortingAlgorithm.UNSORTED:
self.log(u"Sorting using UNSORTED")
elif self.algorithm == IDSortingAlgorithm.LEXICOGRAPHIC:
self.log(u"Sorting using LEXICOGRAPHIC")
tmp = sorted(ids)
elif self.algorithm == IDSortingAlgorithm.NUMERIC:
self.log(u"Sorting using NUMERIC")
tmp = ids
try:
tmp = sorted(tmp, key=extract_int)
except (ValueError, TypeError) as exc:
self.log_exc(u"Not all id values contain a numeric part. Returning the id list unchanged.", exc, False, None)
return tmp | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/idsortingalgorithm.py#L79-L109 |
sort string list | python | def sort(self, *sort):
""" Sort the results.
Define how the results should be sorted. The arguments should be tuples
of string defining the key and direction to sort by. For example
`('name', 'asc')` and `('version', 'desc')`. The first sorte rule is
considered first by the API. See also the API documentation on
`sorting`_.
Arguments:
`*sort` (`tuple`)
The rules to sort by
.. _sorting: https://github.com/XereoNet/SpaceGDN/wiki/API#sorting
"""
self.add_get_param('sort', FILTER_DELIMITER.join(
[ELEMENT_DELIMITER.join(elements) for elements in sort]))
return self | https://github.com/totokaka/pySpaceGDN/blob/55c8be8d751e24873e0a7f7e99d2b715442ec878/pyspacegdn/requests/find_request.py#L73-L91 |
sort string list | python | def sort_by_key(self, keys=None):
"""
:param keys: list of str to sort by, if name starts with -
reverse order
:return: None
"""
keys = keys or self.key_on
keys = keys if isinstance(keys, (list, tuple)) else [keys]
for key in reversed(keys):
reverse, key = (True, key[1:]) if key[0] == '-' else (False, key)
self.table.sort(key=lambda row: row[key], reverse=reverse) | https://github.com/SeabornGames/Table/blob/0c474ef2fb00db0e7cf47e8af91e3556c2e7485a/seaborn_table/table.py#L1371-L1381 |
sort string list | python | def sort_annotations(annotations: List[Tuple[int, int, str]]
) -> List[Tuple[int, int, str]]:
""" Sorts the annotations by their start_time. """
return sorted(annotations, key=lambda x: x[0]) | https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/preprocess/elan.py#L62-L65 |
sort string list | python | def sort_by_fields(items, fields):
"""
Sort a list of objects on the given fields. The field list works analogously to
queryset.order_by(*fields): each field is either a property of the object,
or is prefixed by '-' (e.g. '-name') to indicate reverse ordering.
"""
# To get the desired behaviour, we need to order by keys in reverse order
# See: https://docs.python.org/2/howto/sorting.html#sort-stability-and-complex-sorts
for key in reversed(fields):
# Check if this key has been reversed
reverse = False
if key[0] == '-':
reverse = True
key = key[1:]
# Sort
# Use a tuple of (v is not None, v) as the key, to ensure that None sorts before other values,
# as comparing directly with None breaks on python3
items.sort(key=lambda x: (getattr(x, key) is not None, getattr(x, key)), reverse=reverse) | https://github.com/wagtail/django-modelcluster/blob/bfc8bd755af0ddd49e2aee2f2ca126921573d38b/modelcluster/utils.py#L1-L19 |
sort string list | python | def sort(self, name, start=None, num=None, by=None, get=None,
desc=False, alpha=False, store=None, groups=False):
"""
Sort and return the list, set or sorted set at ``name``.
``start`` and ``num`` allow for paging through the sorted data
``by`` allows using an external key to weight and sort the items.
Use an "*" to indicate where in the key the item value is located
``get`` allows for returning items from external keys rather than the
sorted data itself. Use an "*" to indicate where int he key
the item value is located
``desc`` allows for reversing the sort
``alpha`` allows for sorting lexicographically rather than numerically
``store`` allows for storing the result of the sort into
the key ``store``
``groups`` if set to True and if ``get`` contains at least two
elements, sort will return a list of tuples, each containing the
values fetched from the arguments to ``get``.
"""
if (start is not None and num is None) or \
(num is not None and start is None):
raise DataError("``start`` and ``num`` must both be specified")
pieces = [name]
if by is not None:
pieces.append(Token.get_token('BY'))
pieces.append(by)
if start is not None and num is not None:
pieces.append(Token.get_token('LIMIT'))
pieces.append(start)
pieces.append(num)
if get is not None:
# If get is a string assume we want to get a single value.
# Otherwise assume it's an interable and we want to get multiple
# values. We can't just iterate blindly because strings are
# iterable.
if isinstance(get, (bytes, basestring)):
pieces.append(Token.get_token('GET'))
pieces.append(get)
else:
for g in get:
pieces.append(Token.get_token('GET'))
pieces.append(g)
if desc:
pieces.append(Token.get_token('DESC'))
if alpha:
pieces.append(Token.get_token('ALPHA'))
if store is not None:
pieces.append(Token.get_token('STORE'))
pieces.append(store)
if groups:
if not get or isinstance(get, (bytes, basestring)) or len(get) < 2:
raise DataError('when using "groups" the "get" argument '
'must be specified and contain at least '
'two keys')
options = {'groups': len(get) if groups else None}
return self.execute_command('SORT', *pieces, **options) | https://github.com/andymccurdy/redis-py/blob/cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db/redis/client.py#L1674-L1739 |
sort string list | python | def sort(self, name, start=None, num=None, by=None, get=None,
desc=False, alpha=False, store=None, groups=False):
"""
Sort and return the list, set or sorted set at ``name``.
``start`` and ``num`` allow for paging through the sorted data
``by`` allows using an external key to weight and sort the items.
Use an "*" to indicate where in the key the item value is located
``get`` allows for returning items from external keys rather than the
sorted data itself. Use an "*" to indicate where int he key
the item value is located
``desc`` allows for reversing the sort
``alpha`` allows for sorting lexicographically rather than numerically
``store`` allows for storing the result of the sort into
the key ``store``
``groups`` if set to True and if ``get`` contains at least two
elements, sort will return a list of tuples, each containing the
values fetched from the arguments to ``get``.
"""
with self.pipe as pipe:
res = pipe.sort(self.redis_key(name), start=start, num=num,
by=by, get=get, desc=desc, alpha=alpha,
store=store, groups=groups)
if store:
return res
f = Future()
def cb():
decode = self.valueparse.decode
f.set([decode(v) for v in res.result])
pipe.on_execute(cb)
return f | https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L409-L448 |
sort string list | python | def sort_list_by_index_list(x: List[Any], indexes: List[int]) -> None:
"""
Re-orders ``x`` by the list of ``indexes`` of ``x``, in place.
Example:
.. code-block:: python
from cardinal_pythonlib.lists import sort_list_by_index_list
z = ["a", "b", "c", "d", "e"]
sort_list_by_index_list(z, [4, 0, 1, 2, 3])
z # ["e", "a", "b", "c", "d"]
"""
x[:] = [x[i] for i in indexes] | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/lists.py#L87-L101 |
sort string list | python | def sort(self, key_or_list, direction=None):
"""
Sorts a cursor object based on the input
:param key_or_list: a list/tuple containing the sort specification,
i.e. ('user_number': -1), or a basestring
:param direction: sorting direction, 1 or -1, needed if key_or_list
is a basestring
:return:
"""
# checking input format
sort_specifier = list()
if isinstance(key_or_list, list):
if direction is not None:
raise ValueError('direction can not be set separately '
'if sorting by multiple fields.')
for pair in key_or_list:
if not (isinstance(pair, list) or isinstance(pair, tuple)):
raise TypeError('key pair should be a list or tuple.')
if not len(pair) == 2:
raise ValueError('Need to be (key, direction) pair')
if not isinstance(pair[0], basestring):
raise TypeError('first item in each key pair must '
'be a string')
if not isinstance(pair[1], int) or not abs(pair[1]) == 1:
raise TypeError('bad sort specification.')
sort_specifier = key_or_list
elif isinstance(key_or_list, basestring):
if direction is not None:
if not isinstance(direction, int) or not abs(direction) == 1:
raise TypeError('bad sort specification.')
else:
# default ASCENDING
direction = 1
sort_specifier = [(key_or_list, direction)]
else:
raise ValueError('Wrong input, pass a field name and a direction,'
' or pass a list of (key, direction) pairs.')
# sorting
_cursordat = self.cursordat
total = len(_cursordat)
pre_sect_stack = list()
for pair in sort_specifier:
is_reverse = bool(1-pair[1])
value_stack = list()
for index, data in enumerate(_cursordat):
# get field value
not_found = None
for key in pair[0].split('.'):
not_found = True
if isinstance(data, dict) and key in data:
data = copy.deepcopy(data[key])
not_found = False
elif isinstance(data, list):
if not is_reverse and len(data) == 1:
# MongoDB treat [{data}] as {data}
# when finding fields
if isinstance(data[0], dict) and key in data[0]:
data = copy.deepcopy(data[0][key])
not_found = False
elif is_reverse:
# MongoDB will keep finding field in reverse mode
for _d in data:
if isinstance(_d, dict) and key in _d:
data = copy.deepcopy(_d[key])
not_found = False
break
if not_found:
break
# parsing data for sorting
if not_found:
# treat no match as None
data = None
value = self._order(data, is_reverse)
# read previous section
pre_sect = pre_sect_stack[index] if pre_sect_stack else 0
# inverse if in reverse mode
# for keeping order as ASCENDING after sort
pre_sect = (total - pre_sect) if is_reverse else pre_sect
_ind = (total - index) if is_reverse else index
value_stack.append((pre_sect, value, _ind))
# sorting cursor data
value_stack.sort(reverse=is_reverse)
ordereddat = list()
sect_stack = list()
sect_id = -1
last_dat = None
for dat in value_stack:
# restore if in reverse mode
_ind = (total - dat[-1]) if is_reverse else dat[-1]
ordereddat.append(_cursordat[_ind])
# define section
# maintain the sorting result in next level sorting
if not dat[1] == last_dat:
sect_id += 1
sect_stack.append(sect_id)
last_dat = dat[1]
# save result for next level sorting
_cursordat = ordereddat
pre_sect_stack = sect_stack
# done
self.cursordat = _cursordat
return self | https://github.com/schapman1974/tinymongo/blob/993048059dc0aa789d879b69feb79a0f237a60b3/tinymongo/tinymongo.py#L631-L762 |
sort string list | python | def natural_sort(list_to_sort: Iterable[str]) -> List[str]:
"""
Sorts a list of strings case insensitively as well as numerically.
For example: ['a1', 'A2', 'a3', 'A11', 'a22']
To sort a list in place, don't call this method, which makes a copy. Instead, do this:
my_list.sort(key=natural_keys)
:param list_to_sort: the list being sorted
:return: the list sorted naturally
"""
return sorted(list_to_sort, key=natural_keys) | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/utils.py#L249-L262 |
sort string list | python | def sort(args):
"""
%prog sort fastafile
Sort a list of sequences and output with sorted IDs, etc.
"""
p = OptionParser(sort.__doc__)
p.add_option("--sizes", default=False, action="store_true",
help="Sort by decreasing size [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(p.print_help())
fastafile, = args
sortedfastafile = fastafile.rsplit(".", 1)[0] + ".sorted.fasta"
f = Fasta(fastafile, index=False)
fw = must_open(sortedfastafile, "w")
if opts.sizes:
# Sort by decreasing size
sortlist = sorted(f.itersizes(), key=lambda x: (-x[1], x[0]))
logging.debug("Sort by size: max: {0}, min: {1}".\
format(sortlist[0], sortlist[-1]))
sortlist = [x for x, s in sortlist]
else:
sortlist = sorted(f.iterkeys())
for key in sortlist:
rec = f[key]
SeqIO.write([rec], fw, "fasta")
logging.debug("Sorted file written to `{0}`.".format(sortedfastafile))
fw.close()
return sortedfastafile | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L1006-L1042 |
sort string list | python | def _sort_column(self, column, reverse):
"""Sort a column by its values"""
if tk.DISABLED in self.state():
return
# get list of (value, item) tuple where value is the value in column for the item
l = [(self.set(child, column), child) for child in self.get_children('')]
# sort list using the column type
l.sort(reverse=reverse, key=lambda x: self._column_types[column](x[0]))
# reorder items
for index, (val, child) in enumerate(l):
self.move(child, "", index)
# reverse sorting direction for the next time
self.heading(column, command=lambda: self._sort_column(column, not reverse)) | https://github.com/RedFantom/ttkwidgets/blob/02150322060f867b6e59a175522ef84b09168019/ttkwidgets/table.py#L337-L349 |
sort string list | python | def sortBy(self, val=None):
""" Sort the object's values by a criterion produced by an iterator.
"""
if val is not None:
if _(val).isString():
return self._wrap(sorted(self.obj, key=lambda x,
*args: x.get(val)))
else:
return self._wrap(sorted(self.obj, key=val))
else:
return self._wrap(sorted(self.obj)) | https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L376-L386 |
sort string list | python | def _sort_and_trim(data, reverse=False):
"""Sorts a dictionary with at least two fields on each of them sorting
by the second element.
.. warning::
Right now is hardcoded to 10 elements, improve the command line
interface to allow to send parameters to each command or globally.
"""
threshold = 10
data_list = data.items()
data_list = sorted(
data_list,
key=lambda data_info: data_info[1],
reverse=reverse,
)
return data_list[:threshold] | https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L422-L437 |
sort string list | python | def sort(self, key=None, reverse=False):
"""
Sort the items of this collection according to the optional callable
*key*. If *reverse* is set then the sort order is reversed.
.. note::
This sort requires all items to be retrieved from Redis and stored
in memory.
"""
def sort_trans(pipe):
values = list(self.__iter__(pipe))
values.sort(key=key, reverse=reverse)
pipe.multi()
pipe.delete(self.key)
pipe.rpush(self.key, *(self._pickle(v) for v in values))
if self.writeback:
self.cache = {}
return self._transaction(sort_trans) | https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/lists.py#L500-L520 |
sort string list | python | def sort_kwargs(kwargs, *param_lists):
"""Function to sort keyword arguments and sort them into dictionaries
This function returns dictionaries that contain the keyword arguments
from `kwargs` corresponding given iterables in ``*params``
Parameters
----------
kwargs: dict
Original dictionary
``*param_lists``
iterables of strings, each standing for a possible key in kwargs
Returns
-------
list
len(params) + 1 dictionaries. Each dictionary contains the items of
`kwargs` corresponding to the specified list in ``*param_lists``. The
last dictionary contains the remaining items"""
return chain(
({key: kwargs.pop(key) for key in params.intersection(kwargs)}
for params in map(set, param_lists)), [kwargs]) | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/utils.py#L238-L259 |
sort string list | python | def _sort_itemstrs(items, itemstrs):
"""
Equivalent to `sorted(items)` except if `items` are unorderable, then
string values are used to define an ordering.
"""
# First try to sort items by their normal values
# If that doesnt work, then sort by their string values
import ubelt as ub
try:
# Set ordering is not unique. Sort by strings values instead.
if _peek_isinstance(items, (set, frozenset)):
raise TypeError
sortx = ub.argsort(items)
except TypeError:
sortx = ub.argsort(itemstrs)
itemstrs = [itemstrs[x] for x in sortx]
return itemstrs | https://github.com/Erotemic/ubelt/blob/db802f3ad8abba025db74b54f86e6892b8927325/ubelt/util_format.py#L690-L706 |
sort string list | python | def result_sort(result_list, start_index=0):
"""Sorts a list of results in O(n) in place (since every run is unique)
:param result_list: List of tuples [(run_idx, res), ...]
:param start_index: Index with which to start, every entry before `start_index` is ignored
"""
if len(result_list) < 2:
return result_list
to_sort = result_list[start_index:]
minmax = [x[0] for x in to_sort]
minimum = min(minmax)
maximum = max(minmax)
#print minimum, maximum
sorted_list = [None for _ in range(minimum, maximum + 1)]
for elem in to_sort:
key = elem[0] - minimum
sorted_list[key] = elem
idx_count = start_index
for elem in sorted_list:
if elem is not None:
result_list[idx_count] = elem
idx_count += 1
return result_list | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/helpful_functions.py#L288-L311 |
sort string list | python | def natural_sort(item):
"""
Sort strings that contain numbers correctly. Works in Python 2 and 3.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> l.__repr__()
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']"
"""
dre = re.compile(r'(\d+)')
return [int(s) if s.isdigit() else s.lower() for s in re.split(dre, item)] | https://github.com/xapple/plumbing/blob/4a7706c7722f5996d0ca366f191aff9ac145880a/plumbing/common.py#L286-L296 |
sort string list | python | def sort(key=None, reverse=False, buffersize=None):
"""Sort rows based on some key field or fields. E.g.::
>>> from petlx.push import sort, tocsv
>>> p = sort('foo')
>>> p.pipe(tocsv('sorted_by_foo.csv'))
>>> p.push(sometable)
"""
return SortComponent(key=key, reverse=reverse, buffersize=buffersize) | https://github.com/petl-developers/petlx/blob/54039e30388c7da12407d6b5c3cb865b00436004/petlx/push.py#L246-L256 |
sort string list | python | def dsort(fname, order, has_header=True, frow=0, ofname=None):
r"""
Sort file data.
:param fname: Name of the comma-separated values file to sort
:type fname: FileNameExists_
:param order: Sort order
:type order: :ref:`CsvColFilter`
:param has_header: Flag that indicates whether the comma-separated
values file to sort has column headers in its first line
(True) or not (False)
:type has_header: boolean
:param frow: First data row (starting from 1). If 0 the row where data
starts is auto-detected as the first row that has a number
(integer of float) in at least one of its columns
:type frow: NonNegativeInteger_
:param ofname: Name of the output comma-separated values file, the file
that will contain the sorted data. If None the sorting is
done "in place"
:type ofname: FileName_ or None
.. [[[cog cog.out(exobj.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for pcsv.dsort.dsort
:raises:
* OSError (File *[fname]* could not be found)
* RuntimeError (Argument \`fname\` is not valid)
* RuntimeError (Argument \`frow\` is not valid)
* RuntimeError (Argument \`has_header\` is not valid)
* RuntimeError (Argument \`ofname\` is not valid)
* RuntimeError (Argument \`order\` is not valid)
* RuntimeError (Column headers are not unique in file *[fname]*)
* RuntimeError (File *[fname]* has no valid data)
* RuntimeError (File *[fname]* is empty)
* RuntimeError (Invalid column specification)
* ValueError (Column *[column_identifier]* not found)
.. [[[end]]]
"""
ofname = fname if ofname is None else ofname
obj = CsvFile(fname=fname, has_header=has_header, frow=frow)
obj.dsort(order)
obj.write(fname=ofname, header=has_header, append=False) | https://github.com/pmacosta/pcsv/blob/cd1588c19b0cd58c38bc672e396db940f88ffbd7/pcsv/dsort.py#L37-L93 |
sort string list | python | def sort_nts(self, nt_list, codekey):
"""Sort list of namedtuples such so evidence codes in same order as code2nt."""
# Problem is that some members in the nt_list do NOT have
# codekey=EvidenceCode, then it returns None, which breaks py34 and 35
# The fix here is that for these members, default to -1 (is this valid?)
sortby = lambda nt: self.ev2idx.get(getattr(nt, codekey), -1)
return sorted(nt_list, key=sortby) | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/evidence_codes.py#L110-L116 |
sort string list | python | def sort(self,
key,
by=None,
external=None,
offset=0,
limit=None,
order=None,
alpha=False,
store_as=None):
"""Returns or stores the elements contained in the list, set or sorted
set at key. By default, sorting is numeric and elements are compared by
their value interpreted as double precision floating point number.
The ``external`` parameter is used to specify the
`GET <http://redis.io/commands/sort#retrieving-external-keys>_`
parameter for retrieving external keys. It can be a single string
or a list of strings.
.. note::
**Time complexity**: ``O(N+M*log(M))`` where ``N`` is the number of
elements in the list or set to sort, and ``M`` the number of
returned elements. When the elements are not sorted, complexity is
currently ``O(N)`` as there is a copy step that will be avoided in
next releases.
:param key: The key to get the refcount for
:type key: :class:`str`, :class:`bytes`
:param by: The optional pattern for external sorting keys
:type by: :class:`str`, :class:`bytes`
:param external: Pattern or list of patterns to return external keys
:type external: :class:`str`, :class:`bytes`, list
:param int offset: The starting offset when using limit
:param int limit: The number of elements to return
:param order: The sort order - one of ``ASC`` or ``DESC``
:type order: :class:`str`, :class:`bytes`
:param bool alpha: Sort the results lexicographically
:param store_as: When specified, the key to store the results as
:type store_as: :class:`str`, :class:`bytes`, None
:rtype: list|int
:raises: :exc:`~tredis.exceptions.RedisError`
:raises: :exc:`ValueError`
"""
if order and order not in [b'ASC', b'DESC', 'ASC', 'DESC']:
raise ValueError('invalid sort order "{}"'.format(order))
command = [b'SORT', key]
if by:
command += [b'BY', by]
if external and isinstance(external, list):
for entry in external:
command += [b'GET', entry]
elif external:
command += [b'GET', external]
if limit:
command += [
b'LIMIT',
ascii(offset).encode('utf-8'),
ascii(limit).encode('utf-8')
]
if order:
command.append(order)
if alpha is True:
command.append(b'ALPHA')
if store_as:
command += [b'STORE', store_as]
return self._execute(command) | https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/keys.py#L554-L623 |
sort string list | python | def _sort2sql(self, sort):
"""
RETURN ORDER BY CLAUSE
"""
if not sort:
return ""
return SQL_ORDERBY + sql_list([quote_column(o.field) + (" DESC" if o.sort == -1 else "") for o in sort]) | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/jx_mysql/__init__.py#L314-L320 |
sort string list | python | def natural_sort(item):
"""
Sort strings that contain numbers correctly.
>>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1']
>>> l.sort(key=natural_sort)
>>> print l
"['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']"
"""
if item is None:
return 0
def try_int(s):
try:
return int(s)
except ValueError:
return s
return tuple(map(try_int, re.findall(r'(\d+|\D+)', item))) | https://github.com/kashifrazzaqui/again/blob/09cfbda7650d44447dbb0b27780835e9236741ea/again/utils.py#L10-L27 |
sort string list | python | def sorted(self, by, **kwargs):
"""Sort array by a column.
Parameters
==========
by: str
Name of the columns to sort by(e.g. 'time').
"""
sort_idc = np.argsort(self[by], **kwargs)
return self.__class__(
self[sort_idc],
h5loc=self.h5loc,
split_h5=self.split_h5,
name=self.name
) | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/dataclasses.py#L421-L435 |
sort string list | python | def fmt_pairs(obj, indent=4, sort_key=None):
"""Format and sort a list of pairs, usually for printing.
If sort_key is provided, the value will be passed as the
'key' keyword argument of the sorted() function when
sorting the items. This allows for the input such as
[('A', 3), ('B', 5), ('Z', 1)] to be sorted by the ints
but formatted like so:
l = [('A', 3), ('B', 5), ('Z', 1)]
print(fmt_pairs(l, sort_key=lambda x: x[1]))
Z 1
A 3
B 5
where the default behavior would be:
print(fmt_pairs(l))
A 3
B 5
Z 1
"""
lengths = [len(x[0]) for x in obj]
if not lengths:
return ''
longest = max(lengths)
obj = sorted(obj, key=sort_key)
formatter = '%s{: <%d} {}' % (' ' * indent, longest)
string = '\n'.join([formatter.format(k, v) for k, v in obj])
return string | https://github.com/rackerlabs/simpl/blob/60ed3336a931cd6a7a7246e60f26165d9dc7c99c/simpl/server.py#L278-L308 |
sort string list | python | def sort_list_of_dicts(lst_of_dct, keys, reverse=False, **sort_args):
"""
Sort list of dicts by one or multiple keys.
If the key is not available, sort these to the end.
:param lst_of_dct: input structure. List of dicts.
:param keys: one or more keys in list
:param reverse:
:param sort_args:
:return:
"""
if type(keys) != list:
keys = [keys]
# dcmdir = lst_of_dct[:]
# lst_of_dct.sort(key=lambda x: [x[key] for key in keys], reverse=reverse, **sort_args)
lst_of_dct.sort(key=lambda x: [((False, x[key]) if key in x else (True, 0)) for key in keys], reverse=reverse, **sort_args)
return lst_of_dct | https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L238-L256 |
sort string list | python | def sort_fn_list(fn_list):
"""Sort input filename list by datetime
"""
dt_list = get_dt_list(fn_list)
fn_list_sort = [fn for (dt,fn) in sorted(zip(dt_list,fn_list))]
return fn_list_sort | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L176-L181 |
sort string list | python | def sort2groups(array, gpat=['_R1','_R2']):
""" Sort an array of strings to groups by patterns """
groups = [REGroup(gp) for gp in gpat]
unmatched = []
for item in array:
matched = False
for m in groups:
if m.match(item):
matched = True
break
if not matched: unmatched.append(item)
return [sorted(m.list) for m in groups], sorted(unmatched) | https://github.com/OLC-Bioinformatics/sipprverse/blob/d4f10cdf8e1a39dac0953db61c21c97efc6006de/cgecore/utility.py#L360-L371 |
sort string list | python | def parse_sort_key(identity: str, sort_key_string: str) -> 'Key':
""" Parses a flat key string and returns a key """
parts = sort_key_string.split(Key.PARTITION)
key_type = KeyType.DIMENSION
if parts[2]:
key_type = KeyType.TIMESTAMP
return Key(key_type, identity, parts[0], parts[1].split(Key.DIMENSION_PARTITION)
if parts[1] else [],
parser.parse(parts[2]) if parts[2] else None) | https://github.com/productml/blurr/blob/1b688b2c4a9bbbb2139c58bf0682ddc05a6c24fa/blurr/core/store_key.py#L73-L81 |
sort string list | python | def sortby(listoflists,sortcols):
"""
Sorts a list of lists on the column(s) specified in the sequence
sortcols.
Usage: sortby(listoflists,sortcols)
Returns: sorted list, unchanged column ordering
"""
newlist = abut(colex(listoflists,sortcols),listoflists)
newlist.sort()
try:
numcols = len(sortcols)
except TypeError:
numcols = 1
crit = '[' + str(numcols) + ':]'
newlist = colex(newlist,crit)
return newlist | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/pstat.py#L642-L658 |
sort string list | python | def sort_items(self,items,args=False):
"""
Sort the `self`'s contents, as contained in the list `items` as
specified in `self`'s meta-data.
"""
if self.settings['sort'].lower() == 'src': return
def alpha(i):
return i.name
def permission(i):
if args:
if i.intent == 'in': return 'b'
if i.intent == 'inout': return 'c'
if i.intent == 'out': return 'd'
if i.intent == '': return 'e'
perm = getattr(i, 'permission', '')
if perm == 'public': return 'b'
if perm == 'protected': return 'c'
if perm == 'private': return 'd'
return 'a'
def permission_alpha(i):
return permission(i) + '-' + i.name
def itype(i):
if i.obj == 'variable':
retstr = i.vartype
if retstr == 'class': retstr = 'type'
if i.kind: retstr = retstr + '-' + str(i.kind)
if i.strlen: retstr = retstr + '-' + str(i.strlen)
if i.proto:
retstr = retstr + '-' + i.proto[0]
return retstr
elif i.obj == 'proc':
if i.proctype != 'Function':
return i.proctype.lower()
else:
return i.proctype.lower() + '-' + itype(i.retvar)
else:
return i.obj
def itype_alpha(i):
return itype(i) + '-' + i.name
if self.settings['sort'].lower() == 'alpha':
items.sort(key=alpha)
elif self.settings['sort'].lower() == 'permission':
items.sort(key=permission)
elif self.settings['sort'].lower() == 'permission-alpha':
items.sort(key=permission_alpha)
elif self.settings['sort'].lower() == 'type':
items.sort(key=itype)
elif self.settings['sort'].lower() == 'type-alpha':
items.sort(key=itype_alpha) | https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/sourceform.py#L2402-L2451 |
sort string list | python | def dict_sort(d, k):
"""
Sort a dictionary list by key
:param d: dictionary list
:param k: key
:return: sorted dictionary list
"""
return sorted(d.copy(), key=lambda i: i[k]) | https://github.com/valency/deeputils/blob/27efd91668de0223ed8b07cfadf2151632521520/deeputils/common.py#L85-L92 |
sort string list | python | def sort(self, key, start=None, num=None, by=None, get=None,
desc=False, alpha=False, store=None, groups=False):
'''Sort and return the list, set or sorted set at ``key``.
``start`` and ``num`` allow for paging through the sorted data
``by`` allows using an external key to weight and sort the items.
Use an "*" to indicate where in the key the item value is located
``get`` allows for returning items from external keys rather than the
sorted data itself. Use an "*" to indicate where int he key
the item value is located
``desc`` allows for reversing the sort
``alpha`` allows for sorting lexicographically rather than numerically
``store`` allows for storing the result of the sort into
the key ``store``
``groups`` if set to True and if ``get`` contains at least two
elements, sort will return a list of tuples, each containing the
values fetched from the arguments to ``get``.
'''
if ((start is not None and num is None) or
(num is not None and start is None)):
raise CommandError("``start`` and ``num`` must both be specified")
pieces = [key]
if by is not None:
pieces.append('BY')
pieces.append(by)
if start is not None and num is not None:
pieces.append('LIMIT')
pieces.append(start)
pieces.append(num)
if get is not None:
# If get is a string assume we want to get a single value.
# Otherwise assume it's an interable and we want to get multiple
# values. We can't just iterate blindly because strings are
# iterable.
if isinstance(get, str):
pieces.append('GET')
pieces.append(get)
else:
for g in get:
pieces.append('GET')
pieces.append(g)
if desc:
pieces.append('DESC')
if alpha:
pieces.append('ALPHA')
if store is not None:
pieces.append('STORE')
pieces.append(store)
if groups:
if not get or isinstance(get, str) or len(get) < 2:
raise CommandError('when using "groups" the "get" argument '
'must be specified and contain at least '
'two keys')
options = {'groups': len(get) if groups else None}
return self.execute_command('SORT', *pieces, **options) | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/redis/client.py#L434-L498 |
sort string list | python | def sort_together(iterables, key_list=(0,), reverse=False):
"""Return the input iterables sorted together, with *key_list* as the
priority for sorting. All iterables are trimmed to the length of the
shortest one.
This can be used like the sorting function in a spreadsheet. If each
iterable represents a column of data, the key list determines which
columns are used for sorting.
By default, all iterables are sorted using the ``0``-th iterable::
>>> iterables = [(4, 3, 2, 1), ('a', 'b', 'c', 'd')]
>>> sort_together(iterables)
[(1, 2, 3, 4), ('d', 'c', 'b', 'a')]
Set a different key list to sort according to another iterable.
Specifying multiple keys dictates how ties are broken::
>>> iterables = [(3, 1, 2), (0, 1, 0), ('c', 'b', 'a')]
>>> sort_together(iterables, key_list=(1, 2))
[(2, 3, 1), (0, 0, 1), ('a', 'c', 'b')]
Set *reverse* to ``True`` to sort in descending order.
>>> sort_together([(1, 2, 3), ('c', 'b', 'a')], reverse=True)
[(3, 2, 1), ('a', 'b', 'c')]
"""
return list(zip(*sorted(zip(*iterables),
key=itemgetter(*key_list),
reverse=reverse))) | https://github.com/erikrose/more-itertools/blob/6a91b4e25c8e12fcf9fc2b53cf8ee0fba293e6f9/more_itertools/more.py#L1276-L1306 |
sort string list | python | def sort_by_successors(l, succsOf):
""" Sorts a list, such that if l[b] in succsOf(l[a]) then a < b """
rlut = dict()
nret = 0
todo = list()
for i in l:
rlut[i] = set()
for i in l:
for j in succsOf(i):
rlut[j].add(i)
for i in l:
if len(rlut[i]) == 0:
todo.append(i)
while len(todo) > 0:
i = todo.pop()
nret += 1
yield i
for j in succsOf(i):
rlut[j].remove(i)
if len(rlut[j]) == 0:
todo.append(j)
if nret != len(l):
raise ValueError("Cycle detected") | https://github.com/bwesterb/sarah/blob/a9e46e875dfff1dc11255d714bb736e5eb697809/src/order.py#L23-L45 |
sort string list | python | def sort(self, search):
"""
Add sorting information to the request.
"""
if self._sort:
search = search.sort(*self._sort)
return search | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L364-L370 |
sort string list | python | def sort(self, *args, **kwargs):
'''
http://www.elasticsearch.org/guide/reference/api/search/sort.html
Allows to add one or more sort on specific fields. Each sort can be reversed as well. The sort is defined on a per field level, with special field name for _score to sort by score.
standard arguments are ordered ascending, keyword arguments are fields and you specify the order either asc or desc
'''
if not self.params:
self.params = dict()
self.params['sort'] = list()
for arg in args:
self.params['sort'].append(arg)
for k,v in kwargs.iteritems():
self.params['sort'].append({k : v})
return self | https://github.com/ooici/elasticpy/blob/ec221800a80c39e80d8c31667c5b138da39219f2/elasticpy/search.py#L70-L85 |
sort string list | python | def sort(table, key=None, reverse=False, buffersize=None, tempdir=None,
cache=True):
"""
Sort the table. Field names or indices (from zero) can be used to specify
the key. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... ['C', 2],
... ['A', 9],
... ['A', 6],
... ['F', 1],
... ['D', 10]]
>>> table2 = etl.sort(table1, 'foo')
>>> table2
+-----+-----+
| foo | bar |
+=====+=====+
| 'A' | 9 |
+-----+-----+
| 'A' | 6 |
+-----+-----+
| 'C' | 2 |
+-----+-----+
| 'D' | 10 |
+-----+-----+
| 'F' | 1 |
+-----+-----+
>>> # sorting by compound key is supported
... table3 = etl.sort(table1, key=['foo', 'bar'])
>>> table3
+-----+-----+
| foo | bar |
+=====+=====+
| 'A' | 6 |
+-----+-----+
| 'A' | 9 |
+-----+-----+
| 'C' | 2 |
+-----+-----+
| 'D' | 10 |
+-----+-----+
| 'F' | 1 |
+-----+-----+
>>> # if no key is specified, the default is a lexical sort
... table4 = etl.sort(table1)
>>> table4
+-----+-----+
| foo | bar |
+=====+=====+
| 'A' | 6 |
+-----+-----+
| 'A' | 9 |
+-----+-----+
| 'C' | 2 |
+-----+-----+
| 'D' | 10 |
+-----+-----+
| 'F' | 1 |
+-----+-----+
The `buffersize` argument should be an `int` or `None`.
If the number of rows in the table is less than `buffersize`, the table
will be sorted in memory. Otherwise, the table is sorted in chunks of
no more than `buffersize` rows, each chunk is written to a temporary file,
and then a merge sort is performed on the temporary files.
If `buffersize` is `None`, the value of
`petl.config.sort_buffersize` will be used. By default this is
set to 100000 rows, but can be changed, e.g.::
>>> import petl.config
>>> petl.config.sort_buffersize = 500000
If `petl.config.sort_buffersize` is set to `None`, this forces
all sorting to be done entirely in memory.
By default the results of the sort will be cached, and so a second pass over
the sorted table will yield rows from the cache and will not repeat the
sort operation. To turn off caching, set the `cache` argument to `False`.
"""
return SortView(table, key=key, reverse=reverse, buffersize=buffersize,
tempdir=tempdir, cache=cache) | https://github.com/petl-developers/petl/blob/1d33ca055f7e04e0d28a772041c9fd30c8d415d6/petl/transform/sorts.py#L25-L112 |
sort string list | python | def sort_by_type(file_list):
"""
Sorts a list of files into types.
:param file_list: List of file paths.
:return: {extension: [<list of file paths with that extension>]}
"""
ret_dict = defaultdict(list)
for filepath in file_list:
_, ext = os.path.splitext(filepath)
ret_dict[ext.replace('.', '')].append(filepath)
return ret_dict | https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/utils/general.py#L75-L87 |
sort string list | python | def sort_by(self, *fields, **kwargs):
"""
Indicate how the results should be sorted. This can also be used for
*top-N* style queries
### Parameters
- **fields**: The fields by which to sort. This can be either a single
field or a list of fields. If you wish to specify order, you can
use the `Asc` or `Desc` wrapper classes.
- **max**: Maximum number of results to return. This can be used instead
of `LIMIT` and is also faster.
Example of sorting by `foo` ascending and `bar` descending:
```
sort_by(Asc('@foo'), Desc('@bar'))
```
Return the top 10 customers:
```
AggregateRequest()\
.group_by('@customer', r.sum('@paid').alias(FIELDNAME))\
.sort_by(Desc('@paid'), max=10)
```
"""
self._max = kwargs.get('max', 0)
if isinstance(fields, (string_types, SortDirection)):
fields = [fields]
for f in fields:
if isinstance(f, SortDirection):
self._sortby += [f.field, f.DIRSTRING]
else:
self._sortby.append(f)
return self | https://github.com/RediSearch/redisearch-py/blob/f65d1dd078713cbe9b83584e86655a254d0531ab/redisearch/aggregation.py#L233-L269 |
sort string list | python | def nsorted(
to_sort: Iterable[str],
key: Optional[Callable[[str], Any]] = None
) -> List[str]:
"""Returns a naturally sorted list"""
if key is None:
key_callback = _natural_keys
else:
def key_callback(text: str) -> List[Any]:
return _natural_keys(key(text)) # type: ignore
return sorted(to_sort, key=key_callback) | https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/natural.py#L40-L51 |
sort string list | python | def sorted(self, key=None, reverse=False):
"""
Uses python sort and its passed arguments to sort the input.
>>> seq([2, 1, 4, 3]).sorted()
[1, 2, 3, 4]
:param key: sort using key function
:param reverse: return list reversed or not
:return: sorted sequence
"""
return self._transform(transformations.sorted_t(key=key, reverse=reverse)) | https://github.com/EntilZha/PyFunctional/blob/ac04e4a8552b0c464a7f492f7c9862424867b63e/functional/pipeline.py#L1275-L1286 |
sort string list | python | def sort_by_name(infile, outfile):
'''Sorts input sequence file by sort -d -k1,1, writes sorted output file.'''
seqs = {}
file_to_dict(infile, seqs)
#seqs = list(seqs.values())
#seqs.sort()
fout = utils.open_file_write(outfile)
for name in sorted(seqs):
print(seqs[name], file=fout)
utils.close(fout) | https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/tasks.py#L568-L577 |
sort string list | python | def sorts_query(sortables):
""" Turn the Sortables into a SQL ORDER BY query """
stmts = []
for sortable in sortables:
if sortable.desc:
stmts.append('{} DESC'.format(sortable.field))
else:
stmts.append('{} ASC'.format(sortable.field))
return ' ORDER BY {}'.format(', '.join(stmts)) | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/stores/postgres/store.py#L274-L285 |
sort string list | python | def sort(fields):
'''
Gets a list of <fields> to sort by.
Also supports getting a single string for sorting by one field.
Reverse sort is supported by appending '-' to the field name.
Example: sort(['age', '-height']) will sort by ascending age and descending height.
'''
from pymongo import ASCENDING, DESCENDING
from bson import SON
if isinstance(fields, str):
fields = [fields]
if not hasattr(fields, '__iter__'):
raise ValueError("expected a list of strings or a string. not a {}".format(type(fields)))
sort = []
for field in fields:
if field.startswith('-'):
field = field[1:]
sort.append((field, DESCENDING))
continue
elif field.startswith('+'):
field = field[1:]
sort.append((field, ASCENDING))
return {'$sort': SON(sort)} | https://github.com/alonho/pql/blob/fd8fefcb720b4325d27ab71f15a882fe5f9f77e2/pql/__init__.py#L73-L97 |
sort string list | python | def sort(records: Sequence[Record]) -> List[Record]:
"Sort records into a canonical order, suitable for comparison."
return sorted(records, key=_record_key) | https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/records.py#L86-L88 |
sort string list | python | def _sort_columns(self, columns_list):
"""
Given a list of column names will sort the DataFrame columns to match the given order
:param columns_list: list of column names. Must include all column names
:return: nothing
"""
if not (all([x in columns_list for x in self._columns]) and all([x in self._columns for x in columns_list])):
raise ValueError(
'columns_list must be all in current columns, and all current columns must be in columns_list')
new_sort = [self._columns.index(x) for x in columns_list]
self._data = blist([self._data[x] for x in new_sort]) if self._blist else [self._data[x] for x in new_sort]
self._columns = blist([self._columns[x] for x in new_sort]) if self._blist \
else [self._columns[x] for x in new_sort] | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L126-L139 |
sort string list | python | def sort_values(expr, by, ascending=True):
"""
Sort the collection by values. `sort` is an alias name for `sort_values`
:param expr: collection
:param by: the sequence or sequences to sort
:param ascending: Sort ascending vs. descending. Sepecify list for multiple sort orders.
If this is a list of bools, must match the length of the by
:return: Sorted collection
:Example:
>>> df.sort_values(['name', 'id']) # 1
>>> df.sort(['name', 'id'], ascending=False) # 2
>>> df.sort(['name', 'id'], ascending=[False, True]) # 3
>>> df.sort([-df.name, df.id]) # 4, equal to #3
"""
if not isinstance(by, list):
by = [by, ]
by = [it(expr) if inspect.isfunction(it) else it for it in by]
return SortedCollectionExpr(expr, _sorted_fields=by, _ascending=ascending,
_schema=expr._schema) | https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/expr/collections.py#L121-L142 |
sort string list | python | def items_sort(cls, items):
"""Sort list items, taking into account parent items.
Args:
items (list[gkeepapi.node.ListItem]): Items to sort.
Returns:
list[gkeepapi.node.ListItem]: Sorted items.
"""
class t(tuple):
"""Tuple with element-based sorting"""
def __cmp__(self, other):
for a, b in six.moves.zip_longest(self, other):
if a != b:
if a is None:
return 1
if b is None:
return -1
return a - b
return 0
def __lt__(self, other):
return self.__cmp__(other) < 0
def __gt_(self, other):
return self.__cmp__(other) > 0
def __le__(self, other):
return self.__cmp__(other) <= 0
def __ge_(self, other):
return self.__cmp__(other) >= 0
def __eq__(self, other):
return self.__cmp__(other) == 0
def __ne__(self, other):
return self.__cmp__(other) != 0
def key_func(x):
if x.indented:
return t((int(x.parent_item.sort), int(x.sort)))
return t((int(x.sort), ))
return sorted(items, key=key_func, reverse=True) | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L1359-L1397 |
sort string list | python | def sort(self, key, reverse=False):
"""Sort Table in place, using given fields as sort key.
@param key: if this is a string, it is a comma-separated list of field names,
optionally followed by 'desc' to indicate descending sort instead of the
default ascending sort; if a list or tuple, it is a list or tuple of field names
or field names with ' desc' appended; if it is a function, then it is the
function to be used as the sort key function
@param reverse: (default=False) set to True if results should be in reverse order
@type reverse: bool
@return: self
"""
if isinstance(key, (basestring, list, tuple)):
if isinstance(key, basestring):
attrdefs = [s.strip() for s in key.split(',')]
attr_orders = [(a.split()+['asc', ])[:2] for a in attrdefs]
else:
# attr definitions were already resolved to a sequence by the caller
if isinstance(key[0], basestring):
attr_orders = [(a.split()+['asc', ])[:2] for a in key]
else:
attr_orders = key
attrs = [attr for attr, order in attr_orders]
# special optimization if all orders are ascending or descending
if all(order == 'asc' for attr, order in attr_orders):
self.obs.sort(key=attrgetter(*attrs), reverse=reverse)
elif all(order == 'desc' for attr, order in attr_orders):
self.obs.sort(key=attrgetter(*attrs), reverse=not reverse)
else:
# mix of ascending and descending sorts, have to do succession of sorts
# leftmost attr is the most primary sort key, so reverse attr_orders to do
# succession of sorts from right to left
do_all(self.obs.sort(key=attrgetter(attr), reverse=(order == "desc"))
for attr, order in reversed(attr_orders))
else:
# sorting given a sort key function
keyfn = key
self.obs.sort(key=keyfn, reverse=reverse)
return self | https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L857-L895 |
sort string list | python | def sort_by(self, attr_name, reverse=False):
"""Sort files by one of it's attributes.
**中文文档**
对容器内的WinFile根据其某一个属性升序或者降序排序。
"""
try:
d = dict()
for abspath, winfile in self.files.items():
d[abspath] = getattr(winfile, attr_name)
self.order = [item[0] for item in sorted(
list(d.items()), key=lambda t: t[1], reverse = reverse)]
except AttributeError:
raise ValueError("valid sortable attributes are: "
"abspath, dirname, basename, fname, ext, "
"size_on_disk, atime, ctime, mtime;") | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/filesystem/filesystem.py#L942-L958 |
sort string list | python | def sort_canonical(keyword, stmts):
"""Sort all `stmts` in the canonical order defined by `keyword`.
Return the sorted list. The `stmt` list is not modified.
If `keyword` does not have a canonical order, the list is returned
as is.
"""
try:
(_arg_type, subspec) = stmt_map[keyword]
except KeyError:
return stmts
res = []
# keep the order of data definition statements and case
keep = [s[0] for s in data_def_stmts] + ['case']
for (kw, _spec) in flatten_spec(subspec):
# keep comments before a statement together with that statement
comments = []
for s in stmts:
if s.keyword == '_comment':
comments.append(s)
elif s.keyword == kw and kw not in keep:
res.extend(comments)
comments = []
res.append(s)
else:
comments = []
# then copy all other statements (extensions)
res.extend([stmt for stmt in stmts if stmt not in res])
return res | https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/grammar.py#L799-L828 |
sort string list | python | def multitype_sort(a):
"""
Sort elements of multiple types
x is assumed to contain elements of different types, such that
plain sort would raise a `TypeError`.
Parameters
----------
a : array-like
Array of items to be sorted
Returns
-------
out : list
Items sorted within their type groups.
"""
types = defaultdict(list)
numbers = {int, float, complex}
for x in a:
t = type(x)
if t in numbers:
types['number'].append(x)
else:
types[t].append(x)
for t in types:
types[t] = np.sort(types[t])
return list(chain(*(types[t] for t in types))) | https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/utils.py#L194-L224 |
sort string list | python | def sort_by(self, property, order="asc"):
"""Getting the sorted result by the given property
:@param property, order: "asc"
:@type property, order: string
:@return self
"""
self.__prepare()
if isinstance(self._json_data, list):
if order == "asc":
self._json_data = sorted(
self._json_data,
key=lambda x: x.get(property)
)
else:
self._json_data = sorted(
self._json_data,
key=lambda x: x.get(property),
reverse=True
)
return self | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L446-L468 |
sort string list | python | def sort_dict(self, data, key):
'''Sort a list of dictionaries by dictionary key'''
return sorted(data, key=itemgetter(key)) if data else [] | https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/utils.py#L28-L30 |
sort string list | python | def sort(self, f=lambda d: d["t"]):
"""Sort here works by sorting by timestamp by default"""
list.sort(self, key=f)
return self | https://github.com/connectordb/connectordb-python/blob/2092b0cb30898139a247176bcf433d5a4abde7cb/connectordb/_datapointarray.py#L41-L44 |
sort string list | python | def sort_uri_list_by_name(uri_list, bypassNamespace=False):
"""
Sorts a list of uris
bypassNamespace:
based on the last bit (usually the name after the namespace) of a uri
It checks whether the last bit is specified using a # or just a /, eg:
rdflib.URIRef('http://purl.org/ontology/mo/Vinyl'),
rdflib.URIRef('http://purl.org/vocab/frbr/core#Work')
"""
def get_last_bit(uri_string):
try:
x = uri_string.split("#")[1]
except:
x = uri_string.split("/")[-1]
return x
try:
if bypassNamespace:
return sorted(uri_list, key=lambda x: get_last_bit(x.__str__()))
else:
return sorted(uri_list)
except:
# TODO: do more testing.. maybe use a unicode-safe method instead of __str__
print(
"Error in <sort_uri_list_by_name>: possibly a UnicodeEncodeError")
return uri_list | https://github.com/lambdamusic/Ontospy/blob/eb46cb13792b2b87f21babdf976996318eec7571/ontospy/core/utils.py#L584-L612 |
sort string list | python | def sort_def_dict(def_dict: Dict[str, List[str]]) -> Dict[str, List[str]]:
"""Sort values of the lists of a defaultdict(list)."""
for _, dd_list in def_dict.items():
dd_list.sort()
return def_dict | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/utils/contributors.py#L72-L76 |
sort string list | python | def _sort_text(definition):
""" Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item>
"""
if definition.name.startswith("_"):
# It's a 'hidden' func, put it next last
return 'z' + definition.name
elif definition.scope == 'builtin':
return 'y' + definition.name
# Else put it at the front
return 'a' + definition.name | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/plugins/rope_completion.py#L58-L69 |
sort string list | python | def sortrows(a, i=0, index_out=False, recurse=True):
""" Sorts array "a" by columns i
Parameters
------------
a : np.ndarray
array to be sorted
i : int (optional)
column to be sorted by, taken as 0 by default
index_out : bool (optional)
return the index I such that a(I) = sortrows(a,i). Default = False
recurse : bool (optional)
recursively sort by each of the columns. i.e.
once column i is sort, we sort the smallest column number
etc. True by default.
Returns
--------
a : np.ndarray
The array 'a' sorted in descending order by column i
I : np.ndarray (optional)
The index such that a[I, :] = sortrows(a, i). Only return if
index_out = True
Examples
---------
>>> a = array([[1,2],[3,1],[2,3]])
>>> b = sortrows(a,0)
>>> b
array([[1, 2],
[2, 3],
[3, 1]])
c, I = sortrows(a,1,True)
>>> c
array([[3, 1],
[1, 2],
[2, 3]])
>>> I
array([1, 0, 2])
>>> a[I,:] - c
array([[0, 0],
[0, 0],
[0, 0]])
"""
I = np.argsort(a[:, i])
a = a[I, :]
# We recursively call sortrows to make sure it is sorted best by every
# column
if recurse & (len(a[0]) > i + 1):
for b in np.unique(a[:, i]):
ids = a[:, i] == b
colids = range(i) + range(i+1, len(a[0]))
a[np.ix_(ids, colids)], I2 = sortrows(a[np.ix_(ids, colids)],
0, True, True)
I[ids] = I[np.nonzero(ids)[0][I2]]
if index_out:
return a, I
else:
return a | https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/utils.py#L198-L258 |
sort string list | python | def natural_sort(l, field=None):
'''
based on snippet found at http://stackoverflow.com/a/4836734/2445984
'''
convert = lambda text: int(text) if text.isdigit() else text.lower()
def alphanum_key(key):
if field is not None:
key = getattr(key, field)
if not isinstance(key, str):
key = str(key)
return [convert(c) for c in re.split('([0-9]+)', key)]
return sorted(l, key=alphanum_key) | https://github.com/bids-standard/pybids/blob/30d924ce770622bda0e390d613a8da42a2a20c32/bids/utils.py#L29-L41 |
sort string list | python | def sort_by(self, fieldName, reverse=False):
'''
sort_by - Return a copy of this collection, sorted by the given fieldName.
The fieldName is accessed the same way as other filtering, so it supports custom properties, etc.
@param fieldName <str> - The name of the field on which to sort by
@param reverse <bool> Default False - If True, list will be in reverse order.
@return <QueryableList> - A QueryableList of the same type with the elements sorted based on arguments.
'''
return self.__class__(
sorted(self, key = lambda item : self._get_item_value(item, fieldName), reverse=reverse)
) | https://github.com/kata198/QueryableList/blob/279286d46205ce8268af42e03b75820a7483fddb/QueryableList/Base.py#L180-L194 |
sort string list | python | def sort_rows(self, rows, section):
"""Sort the rows, as appropriate for the section.
:param rows: List of tuples (all same length, same values in each position)
:param section: Name of section, should match const in Differ class
:return: None; rows are sorted in-place
"""
#print("@@ SORT ROWS:\n{}".format(rows))
# Section-specific determination of sort key
if section.lower() == Differ.CHANGED.lower():
sort_key = Differ.CHANGED_DELTA
else:
sort_key = None
if sort_key is not None:
rows.sort(key=itemgetter(sort_key)) | https://github.com/materialsproject/pymatgen-db/blob/02e4351c2cea431407644f49193e8bf43ed39b9a/matgendb/vv/report.py#L478-L492 |