Skip to content

Commit e7c0449

Browse files
authored
Merge pull request #116 from tushushu/wip-apply-method
Implement `apply` method
2 parents 5ae24be + 07fcdd9 commit e7c0449

2 files changed

Lines changed: 36 additions & 2 deletions

File tree

tests/test_base.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,14 @@ def test_methods_no_arg(
133133
('__getitem__', 'int', [1, 2, 3], 1, {'index': 0}),
134134
('__getitem__', 'string', ['foo', 'bar', 'baz'], 'foo', {'index': 0}),
135135
136+
("apply", "bool", [True, False], [
137+
False, True], {"fn": lambda x: x == False},), # noqa: E712
138+
("apply", "float", [1.0, 2.0], [
139+
True, False], {"fn": lambda x: x < 2.0},),
140+
("apply", "int", [1, 2], [3, 5], {"fn": lambda x: x * 2 + 1},),
141+
("apply", "string", ['foo', 'bar'], [
142+
True, False], {"fn": lambda x: x != 'bar'},),
143+
136144
('astype', 'bool', [True, False], [1, 0], {'dtype': 'int'}),
137145
('astype', 'bool', [True, False], [1.0, 0.0], {'dtype': 'float'}),
138146
('astype', 'bool', [True, False], [True, False], {'dtype': 'bool'}),

ulist/python/ulist/core.py

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,32 @@ def append(self, elem: ELEM) -> None:
161161
"""Adds a new element at the end of the self."""
162162
self._values.append(elem)
163163

164+
def apply(
165+
self,
166+
fn: Callable[[UltraFastList], UltraFastList]
167+
) -> UltraFastList:
168+
"""Return the result of fn(self).
169+
170+
Args:
171+
fn (Callable[[UltraFastList], UltraFastList]):
172+
Function to apply to self.
173+
174+
Returns:
175+
UltraFastList: A ulist object.
176+
177+
Examples
178+
--------
179+
>>> import ulist as ul
180+
>>> arr = ul.arange(3)
181+
>>> arr
182+
UltraFastList([0, 1, 2])
183+
184+
>>> result = arr.apply(lambda x: x * 2)
185+
>>> result
186+
UltraFastList([0, 2, 4])
187+
"""
188+
return fn(self)
189+
164190
def argmax(self) -> int:
165191
"""Returns the indices of the maximum values of self."""
166192
assert not isinstance(self._values, (BooleanList, StringList))
@@ -427,8 +453,8 @@ def where(
427453
self,
428454
fn: Callable[[UltraFastList], UltraFastList]
429455
) -> UltraFastList:
430-
"""According to the function, return a ulist with elements of self
431-
correspondingly.
456+
"""Calculate the condition by fn(self), and return a ulist
457+
with elements of self correspondingly.
432458
433459
Args:
434460
fn (Callable[[UltraFastList], UltraFastList]):

0 commit comments

Comments
 (0)