Skip to content

Commit

Permalink
Add audeer.unique()
Browse files Browse the repository at this point in the history
  • Loading branch information
hagenw committed Jul 5, 2024
1 parent ec72190 commit 0e0e37a
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 0 deletions.
1 change: 1 addition & 0 deletions audeer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from audeer.core.utils import sort_versions
from audeer.core.utils import to_list
from audeer.core.utils import uid
from audeer.core.utils import unique
from audeer.core.version import LooseVersion
from audeer.core.version import StrictVersion

Expand Down
23 changes: 23 additions & 0 deletions audeer/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -829,3 +829,26 @@ def uid(
uid = uid[-8:]

return uid


def unique(sequence: typing.Sequence) -> typing.List:
r"""Unique values as list preserving original order.
This is an alternative to ``list(set(x))``,
which returns the values in a non-deterministic order.
Args:
sequence: sequence of values
Returns:
unique values from ``x`` in order of appearance
Examples:
>>> unique([2, 2, 1])
[2, 1]
"""
# https://stackoverflow.com/a/480227
seen = set()
seen_add = seen.add
return [x for x in sequence if not (x in seen or seen_add(x))]
1 change: 1 addition & 0 deletions docs/api-src/audeer.rst
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,4 @@ audeer
to_list
touch
uid
unique
24 changes: 24 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,3 +531,27 @@ def test_uid(from_string, short):
assert uid == uid2
else:
assert uid != uid2


@pytest.mark.parametrize(
"sequence, expected",
[
([], []),
([1], [1]),
([2, 1], [2, 1]),
([2, 1, 2], [2, 1]),
(["a", 1, "a", 1], ["a", 1]),
((1, 1), [1]),
],
)
def test_unique(sequence, expected):
r"""Test audeer.unique().
Should return unique values in original order.
Args:
sequence: sequence if input values
expected: expected unique list
"""
assert audeer.unique(sequence) == expected

0 comments on commit 0e0e37a

Please sign in to comment.