Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add audeer.unique() #149

Merged
merged 4 commits into from
Jul 5, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
25 changes: 25 additions & 0 deletions audeer/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -829,3 +829,28 @@ def uid(
uid = uid[-8:]

return uid


def unique(sequence: typing.Sequence) -> typing.List:
r"""Unique values in its original order.

This is an alternative to ``list(set(x))``,
which does not preserve the original order.

Args:
sequence: sequence of values

Returns:
unique values from ``x`` in order of appearance

Examples:
>>> list(set([2, 2, 1]))
[1, 2]
>>> 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
Loading