pyiter.sequence
Deprecated compatibility module.
The stream implementation now lives in pyiter.stream, and the current
entrypoint is pyiter.it. This module is kept only so that existing code
doing from pyiter.sequence import ... (or importing the deprecated
sequence / seq names) keeps working.
The deprecated entrypoints are defined here (not in pyiter.stream), so
pyiter.stream only carries the current design. Every other public name is
re-exported from pyiter.stream. Please import from pyiter.stream (or the
top-level pyiter package) instead.
1""" 2Deprecated compatibility module. 3 4The stream implementation now lives in `pyiter.stream`, and the current 5entrypoint is `pyiter.it`. This module is kept only so that existing code 6doing `from pyiter.sequence import ...` (or importing the deprecated 7`sequence` / `seq` names) keeps working. 8 9The deprecated entrypoints are *defined here* (not in `pyiter.stream`), so 10`pyiter.stream` only carries the current design. Every other public name is 11re-exported from `pyiter.stream`. Please import from `pyiter.stream` (or the 12top-level `pyiter` package) instead. 13""" 14 15from .stream import ( # re-export for backwards compatibility 16 AutoIncrementIndex, 17 IndexedValue, 18 Stream, 19 StreamProducer, 20 it, 21 is_debugging, 22 none_or, 23 none_or_else, 24 throw, 25) 26 27# region deprecated entrypoints (defined here so pyiter.stream stays clean) 28sequence: StreamProducer = StreamProducer() 29""" 30Deprecated. Use `pyiter.it` instead. 31 32 Example 1: 33>>> sequence('hello', 'world').map(lambda x: x.upper()).to_list() 34['HELLO', 'WORLD'] 35 36 Example 2: 37>>> sequence(['hello', 'world']).map(lambda x: x.upper()).to_list() 38['HELLO', 'WORLD'] 39 40 Example 3: 41>>> sequence(range(10)).map(lambda x: x*x).to_list() 42[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 43""" 44 45seq: StreamProducer = sequence 46""" 47Deprecated. Use `pyiter.it` instead. 48 49 Example 1: 50>>> seq('hello', 'world').map(lambda x: x.upper()).to_list() 51['HELLO', 'WORLD'] 52 53 Example 2: 54>>> seq(['hello', 'world']).map(lambda x: x.upper()).to_list() 55['HELLO', 'WORLD'] 56 57 Example 3: 58>>> seq(range(10)).map(lambda x: x*x).to_list() 59[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 60""" 61 62Sequence = Stream 63""" 64Deprecated. Use [Stream] instead. 65""" 66 67SequenceProducer = StreamProducer 68""" 69Deprecated. Use [StreamProducer] instead. 70""" 71# endregion 72 73__all__ = [ 74 "AutoIncrementIndex", 75 "IndexedValue", 76 "Sequence", 77 "SequenceProducer", 78 "Stream", 79 "StreamProducer", 80 "is_debugging", 81 "it", 82 "none_or", 83 "none_or_else", 84 "seq", 85 "sequence", 86 "throw", 87]
3044class IndexedValue(NamedTuple, Generic[T]): 3045 val: T 3046 idx: int 3047 3048 def __repr__(self) -> str: 3049 return f"IndexedValue({self.idx}, {self.val})"
IndexedValue(val, idx)
Deprecated. Use [Stream] instead.
Deprecated. Use [StreamProducer] instead.
50class Stream(Generic[T], Iterable[T]): 51 """ 52 Given an [iterator] function constructs a [Stream] that returns values through the [Iterator] 53 provided by that function. 54 55 The values are evaluated lazily, and the sequence is potentially infinite. 56 """ 57 58 __transform__: Transform[Any, T] 59 60 def __init__(self, iterable: Union[Iterable[T], Transform[Any, T]]) -> None: 61 super().__init__() 62 63 self.__transform__ = new_transform(iterable) 64 65 @cached_property 66 def transforms(self) -> Iterable[Transform[Any, Any]]: 67 return [*self.__transform__.transforms()] 68 69 @property 70 def data(self) -> List[T]: 71 if self.__transform__.cache is not None: 72 return self.__transform__.cache.copy() 73 if is_debugging(): 74 raise LazyEvaluationException("The sequence has not been evaluated yet.") 75 return self.to_list() 76 77 def dedup(self) -> Stream[T]: 78 """ 79 Removes consecutive repeated elements in the sequence. 80 81 If the sequence is sorted, this removes all duplicates. 82 83 Example 1: 84 >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1'] 85 >>> it(lst).dedup().to_list() 86 ['a1', 'b2', 'a2', 'a1'] 87 88 Example 1: 89 >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1'] 90 >>> it(lst).sorted().dedup().to_list() 91 ['a1', 'a2', 'b2'] 92 """ 93 return self.dedup_by(lambda x: x) 94 95 @overload 96 def dedup_by(self, key_selector: Callable[[T], Any]) -> Stream[T]: ... 97 @overload 98 def dedup_by(self, key_selector: Callable[[T, int], Any]) -> Stream[T]: ... 99 @overload 100 def dedup_by(self, key_selector: Callable[[T, int, Stream[T]], Any]) -> Stream[T]: ... 101 def dedup_by(self, key_selector: Callable[..., Any]) -> Stream[T]: 102 """ 103 Removes all but the first of consecutive elements in the sequence that resolve to the same key. 104 """ 105 return self.dedup_into_group_by(key_selector).map(lambda x: x[0]) 106 107 @overload 108 def dedup_with_count_by(self, key_selector: Callable[[T], Any]) -> Stream[Tuple[T, int]]: ... 109 @overload 110 def dedup_with_count_by( 111 self, key_selector: Callable[[T, int], Any] 112 ) -> Stream[Tuple[T, int]]: ... 113 @overload 114 def dedup_with_count_by( 115 self, key_selector: Callable[[T, int, Stream[T]], Any] 116 ) -> Stream[Tuple[T, int]]: ... 117 def dedup_with_count_by(self, key_selector: Callable[..., Any]) -> Stream[Tuple[T, int]]: 118 """ 119 Removes all but the first of consecutive elements and its count that resolve to the same key. 120 121 Example 1: 122 >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1'] 123 >>> it(lst).dedup_with_count_by(lambda x: x).to_list() 124 [('a1', 2), ('b2', 1), ('a2', 1), ('a1', 1)] 125 126 Example 1: 127 >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1'] 128 >>> it(lst).sorted().dedup_with_count_by(lambda x: x).to_list() 129 [('a1', 3), ('a2', 1), ('b2', 1)] 130 """ 131 return self.dedup_into_group_by(key_selector).map(lambda x: (x[0], len(x))) 132 133 @overload 134 def dedup_into_group_by(self, key_selector: Callable[[T], Any]) -> Stream[List[T]]: ... 135 @overload 136 def dedup_into_group_by(self, key_selector: Callable[[T, int], Any]) -> Stream[List[T]]: ... 137 @overload 138 def dedup_into_group_by( 139 self, key_selector: Callable[[T, int, Stream[T]], Any] 140 ) -> Stream[List[T]]: ... 141 def dedup_into_group_by(self, key_selector: Callable[..., Any]) -> Stream[List[T]]: 142 from .dedup import DedupTransform 143 144 return it(DedupTransform(self, key_selector)) 145 146 @overload 147 def filter(self, predicate: Callable[[T], bool]) -> Stream[T]: ... 148 @overload 149 def filter(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ... 150 @overload 151 def filter(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ... 152 def filter(self, predicate: Callable[..., bool]) -> Stream[T]: 153 """ 154 Returns a Stream containing only elements matching the given [predicate]. 155 156 Example 1: 157 >>> lst = [ 'a1', 'b1', 'b2', 'a2'] 158 >>> it(lst).filter(lambda x: x.startswith('a')).to_list() 159 ['a1', 'a2'] 160 161 Example 2: 162 >>> lst = [ 'a1', 'b1', 'b2', 'a2'] 163 >>> it(lst).filter(lambda x, i: x.startswith('a') or i % 2 == 0 ).to_list() 164 ['a1', 'b2', 'a2'] 165 """ 166 from .filtering import FilteringTransform 167 168 return it(FilteringTransform(self, self.__callback_overload_warpper__(predicate))) 169 170 def filter_is_instance(self, typ: Type[U]) -> Stream[U]: 171 """ 172 Returns a Stream containing all elements that are instances of specified type parameter typ. 173 174 Example 1: 175 >>> lst = [ 'a1', 1, 'b2', 3] 176 >>> it(lst).filter_is_instance(int).to_list() 177 [1, 3] 178 179 """ 180 from .type_guard import TypeGuardTransform, TypeGuard 181 182 def guard(x: T) -> TypeGuard[U]: 183 return isinstance(x, typ) 184 185 return it(TypeGuardTransform(self, guard)) 186 187 @overload 188 def filter_not(self, predicate: Callable[[T], bool]) -> Stream[T]: ... 189 @overload 190 def filter_not(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ... 191 @overload 192 def filter_not(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ... 193 def filter_not(self, predicate: Callable[..., bool]) -> Stream[T]: 194 """ 195 Returns a Stream containing all elements not matching the given [predicate]. 196 197 Example 1: 198 >>> lst = [ 'a1', 'b1', 'b2', 'a2'] 199 >>> it(lst).filter_not(lambda x: x.startswith('a')).to_list() 200 ['b1', 'b2'] 201 202 Example 2: 203 >>> lst = [ 'a1', 'a2', 'b1', 'b2'] 204 >>> it(lst).filter_not(lambda x, i: x.startswith('a') and i % 2 == 0 ).to_list() 205 ['a2', 'b1', 'b2'] 206 """ 207 predicate = self.__callback_overload_warpper__(predicate) 208 return self.filter(lambda x: not predicate(x)) 209 210 @overload 211 def filter_not_none(self: Stream[Optional[U]]) -> Stream[U]: ... 212 @overload 213 def filter_not_none(self: Stream[T]) -> Stream[T]: ... 214 def filter_not_none(self: Stream[Optional[U]]) -> Stream[U]: 215 """ 216 Returns a Stream containing all elements that are not `None`. 217 218 Example 1: 219 >>> lst = [ 'a', None, 'b'] 220 >>> it(lst).filter_not_none().to_list() 221 ['a', 'b'] 222 """ 223 from .type_guard import TypeGuardTransform, TypeGuard 224 225 def guard(x: Optional[U]) -> TypeGuard[U]: 226 return x is not None 227 228 return it(TypeGuardTransform(self, guard)) 229 230 @overload 231 def map(self, transform: Callable[[T], U]) -> Stream[U]: ... 232 @overload 233 def map(self, transform: Callable[[T], U], return_exceptions: Literal[False]) -> Stream[U]: ... 234 @overload 235 def map( 236 self, transform: Callable[[T], U], return_exceptions: Literal[True] 237 ) -> Stream[Union[U, BaseException]]: ... 238 @overload 239 def map(self, transform: Callable[[T, int], U]) -> Stream[U]: ... 240 @overload 241 def map( 242 self, transform: Callable[[T, int], U], return_exceptions: Literal[False] 243 ) -> Stream[U]: ... 244 @overload 245 def map( 246 self, transform: Callable[[T, int], U], return_exceptions: Literal[True] 247 ) -> Stream[Union[U, BaseException]]: ... 248 @overload 249 def map(self, transform: Callable[[T, int, Stream[T]], U]) -> Stream[U]: ... 250 @overload 251 def map( 252 self, transform: Callable[[T, int, Stream[T]], U], return_exceptions: Literal[False] 253 ) -> Stream[U]: ... 254 @overload 255 def map( 256 self, transform: Callable[[T, int, Stream[T]], U], return_exceptions: Literal[True] 257 ) -> Stream[Union[U, BaseException]]: ... 258 def map( 259 self, transform: Callable[..., U], return_exceptions: bool = False 260 ) -> Union[Stream[U], Stream[Union[U, BaseException]]]: 261 """ 262 Returns a Stream containing the results of applying the given [transform] function 263 to each element in the original Stream. 264 265 Example 1: 266 >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}] 267 >>> it(lst).map(lambda x: x['age']).to_list() 268 [12, 13] 269 270 Example 2: 271 >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}] 272 >>> it(lst).map(lambda x, i: x['name'] + str(i)).to_list() 273 ['A0', 'B1'] 274 275 Example 3: 276 >>> lst = ['hi', 'abc'] 277 >>> it(lst).map(len).to_list() 278 [2, 3] 279 """ 280 from .mapping import MappingTransform 281 282 transform = self.__callback_overload_warpper__(transform) 283 if return_exceptions: 284 285 def transform_wrapper(x: T) -> Union[U, BaseException]: 286 try: 287 return transform(x) 288 except BaseException as e: 289 return e 290 291 return it(MappingTransform(self, transform_wrapper)) 292 293 return it(MappingTransform(self, transform)) 294 295 @overload 296 async def map_async(self, transform: Callable[[T], Awaitable[U]]) -> Stream[U]: ... 297 @overload 298 async def map_async( 299 self, 300 transform: Callable[[T, int], Awaitable[U]], 301 return_exceptions: Literal[True], 302 ) -> Stream[Union[U, BaseException]]: ... 303 @overload 304 async def map_async( 305 self, 306 transform: Callable[[T, int, Stream[T]], Awaitable[U]], 307 return_exceptions: Literal[False] = False, 308 ) -> Stream[U]: ... 309 async def map_async( 310 self, transform: Callable[..., Awaitable[U]], return_exceptions: bool = False 311 ) -> Union[Stream[U], Stream[Union[U, BaseException]]]: 312 """ 313 Similar to `.map()` but you can input a async transform then await it. 314 """ 315 from asyncio import gather 316 317 if return_exceptions: 318 return it(await gather(*self.map(transform), return_exceptions=True)) 319 return it(await gather(*self.map(transform))) 320 321 @overload 322 def map_not_none(self, transform: Callable[[T], Optional[U]]) -> Stream[U]: ... 323 @overload 324 def map_not_none(self, transform: Callable[[T, int], Optional[U]]) -> Stream[U]: ... 325 @overload 326 def map_not_none(self, transform: Callable[[T, int, Stream[T]], Optional[U]]) -> Stream[U]: ... 327 def map_not_none(self, transform: Callable[..., Optional[U]]) -> Stream[U]: 328 """ 329 Returns a Stream containing only the non-none results of applying the given [transform] function 330 to each element in the original collection. 331 332 Example 1: 333 >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': None}] 334 >>> it(lst).map_not_none(lambda x: x['age']).to_list() 335 [12] 336 """ 337 return self.map(transform).filter_not_none() # type: ignore 338 339 @overload 340 def parallel_map( 341 self, 342 transform: Callable[[T], U], 343 max_workers: Optional[int] = None, 344 chunksize: int = 1, 345 executor: ParallelMappingTransform.Executor = "Thread", 346 ) -> Stream[U]: ... 347 @overload 348 def parallel_map( 349 self, 350 transform: Callable[[T, int], U], 351 max_workers: Optional[int] = None, 352 chunksize: int = 1, 353 executor: ParallelMappingTransform.Executor = "Thread", 354 ) -> Stream[U]: ... 355 @overload 356 def parallel_map( 357 self, 358 transform: Callable[[T, int, Stream[T]], U], 359 max_workers: Optional[int] = None, 360 chunksize: int = 1, 361 executor: ParallelMappingTransform.Executor = "Thread", 362 ) -> Stream[U]: ... 363 def parallel_map( 364 self, 365 transform: Callable[..., U], 366 max_workers: Optional[int] = None, 367 chunksize: int = 1, 368 executor: ParallelMappingTransform.Executor = "Thread", 369 ) -> Stream[U]: 370 """ 371 Returns a Stream containing the results of applying the given [transform] function 372 to each element in the original Stream. 373 374 Example 1: 375 >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}] 376 >>> it(lst).parallel_map(lambda x: x['age']).to_list() 377 [12, 13] 378 379 Example 2: 380 >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}] 381 >>> it(lst).parallel_map(lambda x: x['age'], max_workers=2).to_list() 382 [12, 13] 383 384 Example 3: 385 >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}] 386 >>> it(lst).parallel_map(lambda x, i: x['age'] + i, max_workers=2).to_list() 387 [12, 14] 388 """ 389 from .parallel_mapping import ParallelMappingTransform 390 391 return it( 392 ParallelMappingTransform( 393 self, 394 self.__callback_overload_warpper__(transform), 395 max_workers, 396 chunksize, 397 executor, 398 ) 399 ) 400 401 @overload 402 def find(self, predicate: Callable[[T], bool]) -> Optional[T]: ... 403 @overload 404 def find(self, predicate: Callable[[T, int], bool]) -> Optional[T]: ... 405 @overload 406 def find(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Optional[T]: ... 407 def find(self, predicate: Callable[..., bool]) -> Optional[T]: 408 """ 409 Returns the first element matching the given [predicate], or `None` if no such element was found. 410 411 Example 1: 412 >>> lst = ['a', 'b', 'c'] 413 >>> it(lst).find(lambda x: x == 'b') 414 'b' 415 """ 416 return self.first_or_none(predicate) 417 418 def find_last(self, predicate: Callable[[T], bool]) -> Optional[T]: 419 """ 420 Returns the last element matching the given [predicate], or `None` if no such element was found. 421 422 Example 1: 423 >>> lst = ['a', 'b', 'c'] 424 >>> it(lst).find_last(lambda x: x == 'b') 425 'b' 426 """ 427 return self.last_or_none(predicate) 428 429 @overload 430 def first(self) -> T: ... 431 @overload 432 def first(self, predicate: Callable[[T], bool]) -> T: ... 433 @overload 434 def first(self, predicate: Callable[[T, int], bool]) -> T: ... 435 @overload 436 def first(self, predicate: Callable[[T, int, Stream[T]], bool]) -> T: ... 437 def first(self, predicate: Optional[Callable[..., bool]] = None) -> T: 438 """ 439 Returns first element. 440 441 Example 1: 442 >>> lst = ['a', 'b', 'c'] 443 >>> it(lst).first() 444 'a' 445 446 Example 2: 447 >>> lst = [] 448 >>> it(lst).first() 449 Traceback (most recent call last): 450 ... 451 ValueError: Stream is empty. 452 453 Example 3: 454 >>> lst = ['a', 'b', 'c'] 455 >>> it(lst).first(lambda x: x == 'b') 456 'b' 457 458 Example 4: 459 >>> lst = ['a', 'b', 'c'] 460 >>> it(lst).first(lambda x: x == 'd') 461 Traceback (most recent call last): 462 ... 463 ValueError: Stream is empty. 464 465 Example 5: 466 >>> lst = [None] 467 >>> it(lst).first() is None 468 True 469 """ 470 for e in self: 471 if predicate is None or predicate(e): 472 return e 473 raise ValueError("Stream is empty.") 474 475 @overload 476 def first_not_none_of(self: Stream[Optional[U]]) -> U: ... 477 @overload 478 def first_not_none_of( 479 self: Stream[Optional[U]], transform: Callable[[Optional[U]], Optional[U]] 480 ) -> U: ... 481 @overload 482 def first_not_none_of( 483 self: Stream[Optional[U]], 484 transform: Callable[[Optional[U], int], Optional[U]], 485 ) -> U: ... 486 @overload 487 def first_not_none_of( 488 self: Stream[Optional[U]], 489 transform: Callable[[Optional[U], int, Stream[Optional[U]]], Optional[U]], 490 ) -> U: ... 491 def first_not_none_of( 492 self: Stream[Optional[U]], 493 transform: Optional[Callable[..., Optional[U]]] = None, 494 ) -> U: 495 """ 496 Returns the first non-`None` result of applying the given [transform] function to each element in the original collection. 497 498 Example 1: 499 >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': 12}] 500 >>> it(lst).first_not_none_of(lambda x: x['age']) 501 12 502 503 Example 2: 504 >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': None}] 505 >>> it(lst).first_not_none_of(lambda x: x['age']) 506 Traceback (most recent call last): 507 ... 508 ValueError: No element of the Stream was transformed to a non-none value. 509 """ 510 511 v = ( 512 self.first_not_none_of_or_none() 513 if transform is None 514 else self.first_not_none_of_or_none(transform) 515 ) 516 if v is None: 517 raise ValueError("No element of the Stream was transformed to a non-none value.") 518 return v 519 520 @overload 521 def first_not_none_of_or_none(self) -> Optional[T]: ... 522 @overload 523 def first_not_none_of_or_none(self, transform: Callable[[T], T]) -> Optional[T]: ... 524 @overload 525 def first_not_none_of_or_none(self, transform: Callable[[T, int], T]) -> Optional[T]: ... 526 @overload 527 def first_not_none_of_or_none( 528 self, transform: Callable[[T, int, Stream[T]], T] 529 ) -> Optional[T]: ... 530 def first_not_none_of_or_none( 531 self, transform: Optional[Callable[..., T]] = None 532 ) -> Optional[T]: 533 """ 534 Returns the first non-`None` result of applying the given [transform] function to each element in the original collection. 535 536 Example 1: 537 >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': 12}] 538 >>> it(lst).first_not_none_of_or_none(lambda x: x['age']) 539 12 540 541 Example 2: 542 >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': None}] 543 >>> it(lst).first_not_none_of_or_none(lambda x: x['age']) is None 544 True 545 """ 546 if transform is None: 547 return self.first_or_none() 548 return self.map_not_none(transform).first_or_none() 549 550 @overload 551 def first_or_none(self) -> Optional[T]: ... 552 @overload 553 def first_or_none(self, predicate: Callable[[T], bool]) -> Optional[T]: ... 554 @overload 555 def first_or_none(self, predicate: Callable[[T, int], bool]) -> Optional[T]: ... 556 @overload 557 def first_or_none(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Optional[T]: ... 558 def first_or_none(self, predicate: Optional[Callable[..., bool]] = None) -> Optional[T]: 559 """ 560 Returns the first element, or `None` if the Stream is empty. 561 562 Example 1: 563 >>> lst = [] 564 >>> it(lst).first_or_none() is None 565 True 566 567 Example 2: 568 >>> lst = ['a', 'b', 'c'] 569 >>> it(lst).first_or_none() 570 'a' 571 572 Example 2: 573 >>> lst = ['a', 'b', 'c'] 574 >>> it(lst).first_or_none(lambda x: x == 'b') 575 'b' 576 """ 577 if predicate is not None: 578 return self.first_or_default(predicate, None) 579 else: 580 return self.first_or_default(None) 581 582 @overload 583 def first_or_default(self, default: U) -> Union[T, U]: ... 584 @overload 585 def first_or_default(self, predicate: Callable[[T], bool], default: U) -> Union[T, U]: ... 586 @overload 587 def first_or_default(self, predicate: Callable[[T, int], bool], default: U) -> Union[T, U]: ... 588 @overload 589 def first_or_default( 590 self, predicate: Callable[[T, int, Stream[T]], bool], default: U 591 ) -> Union[T, U]: ... 592 def first_or_default( # type: ignore 593 self, predicate: Union[Callable[..., bool], U], default: Optional[U] = None 594 ) -> Union[T, U, None]: 595 """ 596 Returns the first element, or the given [default] if the Stream is empty. 597 598 Example 1: 599 >>> lst = [] 600 >>> it(lst).first_or_default('a') 601 'a' 602 603 Example 2: 604 >>> lst = ['b'] 605 >>> it(lst).first_or_default('a') 606 'b' 607 608 Example 3: 609 >>> lst = ['a', 'b', 'c'] 610 >>> it(lst).first_or_default(lambda x: x == 'b', 'd') 611 'b' 612 613 Example 4: 614 >>> lst = [] 615 >>> it(lst).first_or_default(lambda x: x == 'b', 'd') 616 'd' 617 """ 618 seq = self 619 if isinstance(predicate, Callable): 620 seq = self.filter(predicate) # type: ignore 621 else: 622 default = predicate 623 return next(iter(seq), default) 624 625 @overload 626 def last(self) -> T: ... 627 @overload 628 def last(self, predicate: Callable[[T], bool]) -> T: ... 629 @overload 630 def last(self, predicate: Callable[[T, int], bool]) -> T: ... 631 @overload 632 def last(self, predicate: Callable[[T, int, Stream[T]], bool]) -> T: ... 633 def last(self, predicate: Optional[Callable[..., bool]] = None) -> T: 634 """ 635 Returns last element. 636 637 Example 1: 638 >>> lst = ['a', 'b', 'c'] 639 >>> it(lst).last() 640 'c' 641 642 Example 2: 643 >>> lst = [] 644 >>> it(lst).last() 645 Traceback (most recent call last): 646 ... 647 ValueError: Stream is empty. 648 """ 649 v = self.last_or_none(predicate) if predicate is not None else self.last_or_none() 650 if v is None: 651 raise ValueError("Stream is empty.") 652 return v 653 654 @overload 655 def last_or_none(self) -> Optional[T]: ... 656 @overload 657 def last_or_none(self, predicate: Callable[[T], bool]) -> Optional[T]: ... 658 @overload 659 def last_or_none(self, predicate: Callable[[T, int], bool]) -> Optional[T]: ... 660 @overload 661 def last_or_none(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Optional[T]: ... 662 def last_or_none(self, predicate: Optional[Callable[..., bool]] = None) -> Optional[T]: 663 """ 664 Returns the last element matching the given [predicate], or `None` if no such element was found. 665 666 Exmaple 1: 667 >>> lst = ['a', 'b', 'c'] 668 >>> it(lst).last_or_none() 669 'c' 670 671 Exmaple 2: 672 >>> lst = ['a', 'b', 'c'] 673 >>> it(lst).last_or_none(lambda x: x != 'c') 674 'b' 675 676 Exmaple 3: 677 >>> lst = [] 678 >>> it(lst).last_or_none(lambda x: x != 'c') is None 679 True 680 """ 681 last: Optional[T] = None 682 for i in self if predicate is None else self.filter(predicate): 683 last = i 684 return last 685 686 def index_of_or_none(self, element: T) -> Optional[int]: 687 """ 688 Returns first index of [element], or None if the collection does not contain element. 689 690 Example 1: 691 >>> lst = ['a', 'b', 'c'] 692 >>> it(lst).index_of_or_none('b') 693 1 694 695 Example 2: 696 >>> lst = ['a', 'b', 'c'] 697 >>> it(lst).index_of_or_none('d') 698 """ 699 for i, x in enumerate(self): 700 if x == element: 701 return i 702 return None 703 704 def index_of(self, element: T) -> int: 705 """ 706 Returns first index of [element], or -1 if the collection does not contain element. 707 708 Example 1: 709 >>> lst = ['a', 'b', 'c'] 710 >>> it(lst).index_of('b') 711 1 712 713 Example 2: 714 >>> lst = ['a', 'b', 'c'] 715 >>> it(lst).index_of('d') 716 -1 717 """ 718 return none_or(self.index_of_or_none(element), -1) 719 720 def index_of_or(self, element: T, default: int) -> int: 721 """ 722 Returns first index of [element], or default value if the collection does not contain element. 723 724 Example 1: 725 >>> lst = ['a', 'b', 'c'] 726 >>> it(lst).index_of_or('b', 1) 727 1 728 729 Example 2: 730 >>> lst = ['a', 'b', 'c'] 731 >>> it(lst).index_of_or('d', 0) 732 0 733 """ 734 return none_or(self.index_of_or_none(element), default) 735 736 def index_of_or_else(self, element: T, f: Callable[[], int]) -> int: 737 """ 738 Returns first index of [element], or computes the value from a callback if the collection does not contain element. 739 740 Example 1: 741 >>> lst = ['a', 'b', 'c'] 742 >>> it(lst).index_of_or_else('b', lambda: 2) 743 1 744 745 Example 2: 746 >>> lst = ['a', 'b', 'c'] 747 >>> it(lst).index_of_or_else('d', lambda: 0) 748 0 749 """ 750 return none_or_else(self.index_of_or_none(element), f) 751 752 def last_index_of_or_none(self, element: T) -> Optional[int]: 753 """ 754 Returns last index of [element], or None if the collection does not contain element. 755 756 Example 1: 757 >>> lst = ['a', 'b', 'c', 'b'] 758 >>> it(lst).last_index_of_or_none('b') 759 3 760 761 Example 2: 762 >>> lst = ['a', 'b', 'c'] 763 >>> it(lst).last_index_of_or_none('d') 764 """ 765 seq = self.reversed() 766 last_idx = len(seq) - 1 767 for i, x in enumerate(seq): 768 if x == element: 769 return last_idx - i 770 return None 771 772 def last_index_of(self, element: T) -> int: 773 """ 774 Returns last index of [element], or -1 if the collection does not contain element. 775 776 Example 1: 777 >>> lst = ['a', 'b', 'c', 'b'] 778 >>> it(lst).last_index_of('b') 779 3 780 781 Example 2: 782 >>> lst = ['a', 'b', 'c'] 783 >>> it(lst).last_index_of('d') 784 -1 785 """ 786 return none_or(self.last_index_of_or_none(element), -1) 787 788 def last_index_of_or(self, element: T, default: int) -> int: 789 """ 790 Returns last index of [element], or default value if the collection does not contain element. 791 792 Example 1: 793 >>> lst = ['a', 'b', 'c', 'b'] 794 >>> it(lst).last_index_of_or('b', 0) 795 3 796 797 Example 2: 798 >>> lst = ['a', 'b', 'c'] 799 >>> it(lst).last_index_of_or('d', len(lst)) 800 3 801 """ 802 return none_or(self.last_index_of_or_none(element), default) 803 804 def last_index_of_or_else(self, element: T, f: Callable[[], int]) -> int: 805 """ 806 Returns last index of [element], or computes the value from a callback if the collection does not contain element. 807 808 Example 1: 809 >>> lst = ['a', 'b', 'c', 'b'] 810 >>> it(lst).last_index_of_or_else('b', lambda: 0) 811 3 812 813 Example 2: 814 >>> lst = ['a', 'b', 'c'] 815 >>> it(lst).last_index_of_or_else('d', lambda: len(lst)) 816 3 817 """ 818 return none_or_else(self.last_index_of_or_none(element), f) 819 820 @overload 821 def index_of_first_or_none(self, predicate: Callable[[T], bool]) -> Optional[int]: ... 822 @overload 823 def index_of_first_or_none(self, predicate: Callable[[T, int], bool]) -> Optional[int]: ... 824 @overload 825 def index_of_first_or_none( 826 self, predicate: Callable[[T, int, Stream[T]], bool] 827 ) -> Optional[int]: ... 828 def index_of_first_or_none(self, predicate: Callable[..., bool]) -> Optional[int]: 829 """ 830 Returns first index of element matching the given [predicate], or None if no such element was found. 831 832 Example 1: 833 >>> lst = ['a', 'b', 'c'] 834 >>> it(lst).index_of_first_or_none(lambda x: x == 'b') 835 1 836 837 Example 2: 838 >>> lst = ['a', 'b', 'c'] 839 >>> it(lst).index_of_first_or_none(lambda x: x == 'd') 840 """ 841 predicate = self.__callback_overload_warpper__(predicate) 842 for i, x in enumerate(self): 843 if predicate(x): 844 return i 845 return None 846 847 @overload 848 def index_of_first(self, predicate: Callable[[T], bool]) -> int: ... 849 @overload 850 def index_of_first(self, predicate: Callable[[T, int], bool]) -> int: ... 851 @overload 852 def index_of_first(self, predicate: Callable[[T, int, Stream[T]], bool]) -> int: ... 853 def index_of_first(self, predicate: Callable[..., bool]) -> int: 854 """ 855 Returns first index of element matching the given [predicate], or -1 if no such element was found. 856 857 Example 1: 858 >>> lst = ['a', 'b', 'c'] 859 >>> it(lst).index_of_first(lambda x: x == 'b') 860 1 861 862 Example 2: 863 >>> lst = ['a', 'b', 'c'] 864 >>> it(lst).index_of_first(lambda x: x == 'd') 865 -1 866 867 Example 3: 868 >>> lst = ['a', 'b', 'c'] 869 >>> it(lst).index_of_first(lambda x: x == 'a') 870 0 871 """ 872 return none_or(self.index_of_first_or_none(predicate), -1) 873 874 @overload 875 def index_of_first_or(self, predicate: Callable[[T], bool], default: int) -> int: ... 876 @overload 877 def index_of_first_or(self, predicate: Callable[[T, int], bool], default: int) -> int: ... 878 @overload 879 def index_of_first_or( 880 self, predicate: Callable[[T, int, Stream[T]], bool], default: int 881 ) -> int: ... 882 def index_of_first_or(self, predicate: Callable[..., bool], default: int) -> int: 883 """ 884 Returns first index of element matching the given [predicate], or default value if no such element was found. 885 886 Example 1: 887 >>> lst = ['a', 'b', 'c'] 888 >>> it(lst).index_of_first_or(lambda x: x == 'b', 0) 889 1 890 891 Example 2: 892 >>> lst = ['a', 'b', 'c'] 893 >>> it(lst).index_of_first_or(lambda x: x == 'd', 0) 894 0 895 896 Example 3: 897 >>> lst = ['a', 'b', 'c'] 898 >>> it(lst).index_of_first_or(lambda x: x == 'a', 0) 899 0 900 """ 901 return none_or(self.index_of_first_or_none(predicate), default) 902 903 @overload 904 def index_of_first_or_else( 905 self, predicate: Callable[[T], bool], f: Callable[[], int] 906 ) -> int: ... 907 @overload 908 def index_of_first_or_else( 909 self, predicate: Callable[[T, int], bool], f: Callable[[], int] 910 ) -> int: ... 911 @overload 912 def index_of_first_or_else( 913 self, predicate: Callable[[T, int, Stream[T]], bool], f: Callable[[], int] 914 ) -> int: ... 915 def index_of_first_or_else(self, predicate: Callable[..., bool], f: Callable[[], int]) -> int: 916 """ 917 Returns first index of element matching the given [predicate], or computes the value from a callback if no such element was found. 918 919 Example 1: 920 >>> lst = ['a', 'b', 'c'] 921 >>> it(lst).index_of_first_or_else(lambda x: x == 'b', lambda: len(lst)) 922 1 923 924 Example 2: 925 >>> lst = ['a', 'b', 'c'] 926 >>> it(lst).index_of_first_or_else(lambda x: x == 'd', lambda: len(lst)) 927 3 928 929 Example 3: 930 >>> lst = ['a', 'b', 'c'] 931 >>> it(lst).index_of_first_or_else(lambda x: x == 'a', lambda: len(lst)) 932 0 933 """ 934 return none_or_else(self.index_of_first_or_none(predicate), f) 935 936 @overload 937 def index_of_last_or_none(self, predicate: Callable[[T], bool]) -> Optional[int]: ... 938 @overload 939 def index_of_last_or_none(self, predicate: Callable[[T, int], bool]) -> Optional[int]: ... 940 @overload 941 def index_of_last_or_none( 942 self, predicate: Callable[[T, int, Stream[T]], bool] 943 ) -> Optional[int]: ... 944 def index_of_last_or_none(self, predicate: Callable[..., bool]) -> Optional[int]: 945 """ 946 Returns last index of element matching the given [predicate], or -1 if no such element was found. 947 948 Example 1: 949 >>> lst = ['a', 'b', 'c', 'b'] 950 >>> it(lst).index_of_last_or_none(lambda x: x == 'b') 951 3 952 953 Example 2: 954 >>> lst = ['a', 'b', 'c'] 955 >>> it(lst).index_of_last_or_none(lambda x: x == 'd') 956 """ 957 seq = self.reversed() 958 last_idx = len(seq) - 1 959 predicate = self.__callback_overload_warpper__(predicate) 960 for i, x in enumerate(seq): 961 if predicate(x): 962 return last_idx - i 963 return None 964 965 @overload 966 def index_of_last(self, predicate: Callable[[T], bool]) -> int: ... 967 @overload 968 def index_of_last(self, predicate: Callable[[T, int], bool]) -> int: ... 969 @overload 970 def index_of_last(self, predicate: Callable[[T, int, Stream[T]], bool]) -> int: ... 971 def index_of_last(self, predicate: Callable[..., bool]) -> int: 972 """ 973 Returns last index of element matching the given [predicate], or -1 if no such element was found. 974 975 Example 1: 976 >>> lst = ['a', 'b', 'c', 'b'] 977 >>> it(lst).index_of_last(lambda x: x == 'b') 978 3 979 980 Example 2: 981 >>> lst = ['a', 'b', 'c'] 982 >>> it(lst).index_of_last(lambda x: x == 'd') 983 -1 984 985 Example 3: 986 >>> lst = ['a', 'b', 'c'] 987 >>> it(lst).index_of_last(lambda x: x == 'a') 988 0 989 """ 990 return none_or(self.index_of_last_or_none(predicate), -1) 991 992 @overload 993 def index_of_last_or(self, predicate: Callable[[T], bool], default: int) -> int: ... 994 @overload 995 def index_of_last_or(self, predicate: Callable[[T, int], bool], default: int) -> int: ... 996 @overload 997 def index_of_last_or( 998 self, predicate: Callable[[T, int, Stream[T]], bool], default: int 999 ) -> int: ... 1000 def index_of_last_or(self, predicate: Callable[..., bool], default: int) -> int: 1001 """ 1002 Returns last index of element matching the given [predicate], or default value if no such element was found. 1003 1004 Example 1: 1005 >>> lst = ['a', 'b', 'c', 'b'] 1006 >>> it(lst).index_of_last_or(lambda x: x == 'b', 0) 1007 3 1008 1009 Example 2: 1010 >>> lst = ['a', 'b', 'c'] 1011 >>> it(lst).index_of_last_or(lambda x: x == 'd', -99) 1012 -99 1013 1014 Example 3: 1015 >>> lst = ['a', 'b', 'c'] 1016 >>> it(lst).index_of_last_or(lambda x: x == 'a', 0) 1017 0 1018 """ 1019 return none_or(self.index_of_last_or_none(predicate), default) 1020 1021 @overload 1022 def index_of_last_or_else( 1023 self, predicate: Callable[[T], bool], f: Callable[[], int] 1024 ) -> int: ... 1025 @overload 1026 def index_of_last_or_else( 1027 self, predicate: Callable[[T, int], bool], f: Callable[[], int] 1028 ) -> int: ... 1029 @overload 1030 def index_of_last_or_else( 1031 self, predicate: Callable[[T, int, Stream[T]], bool], f: Callable[[], int] 1032 ) -> int: ... 1033 def index_of_last_or_else(self, predicate: Callable[..., bool], f: Callable[[], int]) -> int: 1034 """ 1035 Returns last index of element matching the given [predicate], or default value if no such element was found. 1036 1037 Example 1: 1038 >>> lst = ['a', 'b', 'c', 'b'] 1039 >>> it(lst).index_of_last_or_else(lambda x: x == 'b', lambda: -len(lst)) 1040 3 1041 1042 Example 2: 1043 >>> lst = ['a', 'b', 'c'] 1044 >>> it(lst).index_of_last_or_else(lambda x: x == 'd', lambda: -len(lst)) 1045 -3 1046 1047 Example 3: 1048 >>> lst = ['a', 'b', 'c'] 1049 >>> it(lst).index_of_last_or_else(lambda x: x == 'a', lambda: -len(lst)) 1050 0 1051 """ 1052 return none_or_else(self.index_of_last_or_none(predicate), f) 1053 1054 @overload 1055 def single(self) -> T: ... 1056 @overload 1057 def single(self, predicate: Callable[[T], bool]) -> T: ... 1058 @overload 1059 def single(self, predicate: Callable[[T, int], bool]) -> T: ... 1060 @overload 1061 def single(self, predicate: Callable[[T, int, Stream[T]], bool]) -> T: ... 1062 def single(self, predicate: Optional[Callable[..., bool]] = None) -> T: 1063 """ 1064 Returns the single element matching the given [predicate], or throws exception if there is no 1065 or more than one matching element. 1066 1067 Exmaple 1: 1068 >>> lst = ['a'] 1069 >>> it(lst).single() 1070 'a' 1071 1072 Exmaple 2: 1073 >>> lst = [] 1074 >>> it(lst).single() is None 1075 Traceback (most recent call last): 1076 ... 1077 ValueError: Stream contains no element matching the predicate. 1078 1079 Exmaple 2: 1080 >>> lst = ['a', 'b'] 1081 >>> it(lst).single() is None 1082 Traceback (most recent call last): 1083 ... 1084 ValueError: Stream contains more than one matching element. 1085 """ 1086 single: Optional[T] = None 1087 found = False 1088 for i in self if predicate is None else self.filter(predicate): 1089 if found: 1090 raise ValueError("Stream contains more than one matching element.") 1091 single = i 1092 found = True 1093 if single is None: 1094 raise ValueError("Stream contains no element matching the predicate.") 1095 return single 1096 1097 @overload 1098 def single_or_none(self) -> Optional[T]: ... 1099 @overload 1100 def single_or_none(self, predicate: Callable[[T], bool]) -> Optional[T]: ... 1101 @overload 1102 def single_or_none(self, predicate: Callable[[T, int], bool]) -> Optional[T]: ... 1103 @overload 1104 def single_or_none(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Optional[T]: ... 1105 def single_or_none(self, predicate: Optional[Callable[..., bool]] = None) -> Optional[T]: 1106 """ 1107 Returns the single element matching the given [predicate], or `None` if element was not found 1108 or more than one element was found. 1109 1110 Exmaple 1: 1111 >>> lst = ['a'] 1112 >>> it(lst).single_or_none() 1113 'a' 1114 1115 Exmaple 2: 1116 >>> lst = [] 1117 >>> it(lst).single_or_none() 1118 1119 Exmaple 2: 1120 >>> lst = ['a', 'b'] 1121 >>> it(lst).single_or_none() 1122 1123 """ 1124 single: Optional[T] = None 1125 found = False 1126 for i in self if predicate is None else self.filter(predicate): 1127 if found: 1128 return None 1129 single = i 1130 found = True 1131 if not found: 1132 return None 1133 return single 1134 1135 # noinspection PyShadowingNames 1136 def drop(self, n: int) -> Stream[T]: 1137 """ 1138 Returns a Stream containing all elements except first [n] elements. 1139 1140 Example 1: 1141 >>> lst = ['a', 'b', 'c'] 1142 >>> it(lst).drop(0).to_list() 1143 ['a', 'b', 'c'] 1144 1145 Example 2: 1146 >>> lst = ['a', 'b', 'c'] 1147 >>> it(lst).drop(1).to_list() 1148 ['b', 'c'] 1149 1150 Example 2: 1151 >>> lst = ['a', 'b', 'c'] 1152 >>> it(lst).drop(4).to_list() 1153 [] 1154 """ 1155 if n < 0: 1156 raise ValueError(f"Requested element count {n} is less than zero.") 1157 if n == 0: 1158 return self 1159 1160 from .drop import DropTransform 1161 1162 return it(DropTransform(self, n)) 1163 1164 # noinspection PyShadowingNames 1165 @overload 1166 def drop_while(self, predicate: Callable[[T], bool]) -> Stream[T]: ... 1167 @overload 1168 def drop_while(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ... 1169 @overload 1170 def drop_while(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ... 1171 def drop_while(self, predicate: Callable[..., bool]) -> Stream[T]: 1172 """ 1173 Returns a Stream containing all elements except first elements that satisfy the given [predicate]. 1174 1175 Example 1: 1176 >>> lst = [1, 2, 3, 4, 1] 1177 >>> it(lst).drop_while(lambda x: x < 3 ).to_list() 1178 [3, 4, 1] 1179 """ 1180 from .drop_while import DropWhileTransform 1181 1182 return it(DropWhileTransform(self, self.__callback_overload_warpper__(predicate))) 1183 1184 # noinspection PyShadowingNames 1185 @overload 1186 def drop_until(self, predicate: Callable[[T], bool]) -> Stream[T]: ... 1187 @overload 1188 def drop_until(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ... 1189 @overload 1190 def drop_until(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ... 1191 def drop_until(self, predicate: Callable[..., bool]) -> Stream[T]: 1192 """ 1193 Returns a Stream containing all elements except the first elements dropped until the first element that satisfies the given [predicate]. 1194 1195 Example 1: 1196 >>> lst = [1, 2, 3, 4, 1] 1197 >>> it(lst).drop_until(lambda x: x >= 3).to_list() 1198 [3, 4, 1] 1199 1200 Example 2: 1201 >>> lst = [1, 2, 1, 4] 1202 >>> it(lst).drop_until(lambda x: x == 4).to_list() 1203 [4] 1204 """ 1205 from .drop_until import DropUntilTransform 1206 1207 return it(DropUntilTransform(self, self.__callback_overload_warpper__(predicate))) 1208 1209 def drop_last(self, n: int) -> Stream[T]: 1210 """ 1211 Returns a Stream containing all elements except last [n] elements. 1212 1213 Example 1: 1214 >>> lst = ['a', 'b', 'c'] 1215 >>> it(lst).drop_last(0).to_list() 1216 ['a', 'b', 'c'] 1217 1218 Example 2: 1219 >>> lst = ['a', 'b', 'c'] 1220 >>> it(lst).drop_last(1).to_list() 1221 ['a', 'b'] 1222 1223 Example 3: 1224 >>> lst = ['a', 'b', 'c'] 1225 >>> it(lst).drop_last(4).to_list() 1226 [] 1227 """ 1228 if n < 0: 1229 raise ValueError(f"Requested element count {n} is less than zero.") 1230 if n == 0: 1231 return self 1232 1233 size = len(self) 1234 if size <= n: 1235 return Stream([]) 1236 return self.take(size - n) 1237 1238 def skip(self, n: int) -> Stream[T]: 1239 """ 1240 Returns a Stream containing all elements except first [n] elements. 1241 1242 Example 1: 1243 >>> lst = ['a', 'b', 'c'] 1244 >>> it(lst).skip(0).to_list() 1245 ['a', 'b', 'c'] 1246 1247 Example 2: 1248 >>> lst = ['a', 'b', 'c'] 1249 >>> it(lst).skip(1).to_list() 1250 ['b', 'c'] 1251 1252 Example 2: 1253 >>> lst = ['a', 'b', 'c'] 1254 >>> it(lst).skip(4).to_list() 1255 [] 1256 """ 1257 return self.drop(n) 1258 1259 @overload 1260 def skip_while(self, predicate: Callable[[T], bool]) -> Stream[T]: ... 1261 @overload 1262 def skip_while(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ... 1263 @overload 1264 def skip_while(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ... 1265 def skip_while(self, predicate: Callable[..., bool]) -> Stream[T]: 1266 """ 1267 Returns a Stream containing all elements except first elements that satisfy the given [predicate]. 1268 1269 Example 1: 1270 >>> lst = [1, 2, 3, 4, 1] 1271 >>> it(lst).skip_while(lambda x: x < 3 ).to_list() 1272 [3, 4, 1] 1273 """ 1274 return self.drop_while(predicate) 1275 1276 def take(self, n: int) -> Stream[T]: 1277 """ 1278 Returns an Stream containing first [n] elements. 1279 1280 Example 1: 1281 >>> a = ['a', 'b', 'c'] 1282 >>> it(a).take(0).to_list() 1283 [] 1284 1285 Example 2: 1286 >>> a = ['a', 'b', 'c'] 1287 >>> it(a).take(2).to_list() 1288 ['a', 'b'] 1289 """ 1290 if n < 0: 1291 raise ValueError(f"Requested element count {n} is less than zero.") 1292 if n == 0: 1293 return Stream([]) 1294 from .take import TakeTransform 1295 1296 return it(TakeTransform(self, n)) 1297 1298 # noinspection PyShadowingNames 1299 @overload 1300 def take_while(self, predicate: Callable[[T], bool]) -> Stream[T]: ... 1301 @overload 1302 def take_while(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ... 1303 @overload 1304 def take_while(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ... 1305 def take_while(self, predicate: Callable[..., bool]) -> Stream[T]: 1306 """ 1307 Returns an Stream containing first elements satisfying the given [predicate]. 1308 1309 Example 1: 1310 >>> lst = ['a', 'b', 'c', 'd'] 1311 >>> it(lst).take_while(lambda x: x in ['a', 'b']).to_list() 1312 ['a', 'b'] 1313 """ 1314 from .take_while import TakeWhileTransform 1315 1316 return it(TakeWhileTransform(self, self.__callback_overload_warpper__(predicate))) 1317 1318 # noinspection PyShadowingNames 1319 @overload 1320 def take_until(self, predicate: Callable[[T], bool]) -> Stream[T]: ... 1321 @overload 1322 def take_until(self, predicate: Callable[[T, int], bool]) -> Stream[T]: ... 1323 @overload 1324 def take_until(self, predicate: Callable[[T, int, Stream[T]], bool]) -> Stream[T]: ... 1325 def take_until(self, predicate: Callable[..., bool]) -> Stream[T]: 1326 """ 1327 Returns a Stream containing the first elements taken until the first element that satisfies the given [predicate]. 1328 1329 Example 1: 1330 >>> lst = [1, 2, 3, 4] 1331 >>> it(lst).take_until(lambda x: x > 2).to_list() 1332 [1, 2] 1333 1334 Example 2: 1335 >>> lst = [1, 2, 3, 4] 1336 >>> it(lst).take_until(lambda x: x > 10).to_list() 1337 [1, 2, 3, 4] 1338 """ 1339 from .take_until import TakeUntilTransform 1340 1341 return it(TakeUntilTransform(self, self.__callback_overload_warpper__(predicate))) 1342 1343 def take_last(self, n: int) -> Stream[T]: 1344 """ 1345 Returns an Stream containing last [n] elements. 1346 1347 Example 1: 1348 >>> a = ['a', 'b', 'c'] 1349 >>> it(a).take_last(0).to_list() 1350 [] 1351 1352 Example 2: 1353 >>> a = ['a', 'b', 'c'] 1354 >>> it(a).take_last(2).to_list() 1355 ['b', 'c'] 1356 1357 Example 3: 1358 >>> a = ['a', 'b', 'c'] 1359 >>> it(a).take_last(10).to_list() 1360 ['a', 'b', 'c'] 1361 """ 1362 if n < 0: 1363 raise ValueError(f"Requested element count {n} is less than zero.") 1364 if n == 0: 1365 return Stream([]) 1366 1367 return self.drop(max(len(self) - n, 0)) 1368 1369 # noinspection PyShadowingNames 1370 def sorted(self) -> Stream[T]: 1371 """ 1372 Returns an Stream that yields elements of this Stream sorted according to their natural sort order. 1373 1374 Example 1: 1375 >>> lst = ['b', 'a', 'e', 'c'] 1376 >>> it(lst).sorted().to_list() 1377 ['a', 'b', 'c', 'e'] 1378 1379 Example 2: 1380 >>> lst = [2, 1, 4, 3] 1381 >>> it(lst).sorted().to_list() 1382 [1, 2, 3, 4] 1383 """ 1384 lst = list(self) 1385 lst.sort() # type: ignore 1386 return it(lst) 1387 1388 # noinspection PyShadowingNames 1389 @overload 1390 def sorted_by(self, key_selector: Callable[[T], SupportsRichComparisonT]) -> Stream[T]: ... 1391 @overload 1392 def sorted_by(self, key_selector: Callable[[T, int], SupportsRichComparisonT]) -> Stream[T]: ... 1393 @overload 1394 def sorted_by( 1395 self, key_selector: Callable[[T, int, Stream[T]], SupportsRichComparisonT] 1396 ) -> Stream[T]: ... 1397 def sorted_by(self, key_selector: Callable[..., SupportsRichComparisonT]) -> Stream[T]: 1398 """ 1399 Returns a sequence that yields elements of this sequence sorted according to natural sort 1400 order of the value returned by specified [key_selector] function. 1401 1402 Example 1: 1403 >>> lst = [ {'name': 'A', 'age': 12 }, {'name': 'C', 'age': 10 }, {'name': 'B', 'age': 11 } ] 1404 >>> it(lst).sorted_by(lambda x: x['name']).to_list() 1405 [{'name': 'A', 'age': 12}, {'name': 'B', 'age': 11}, {'name': 'C', 'age': 10}] 1406 >>> it(lst).sorted_by(lambda x: x['age']).to_list() 1407 [{'name': 'C', 'age': 10}, {'name': 'B', 'age': 11}, {'name': 'A', 'age': 12}] 1408 """ 1409 lst = list(self) 1410 lst.sort(key=self.__callback_overload_warpper__(key_selector)) 1411 return it(lst) 1412 1413 def sorted_descending(self) -> Stream[T]: 1414 """ 1415 Returns a Stream of all elements sorted descending according to their natural sort order. 1416 1417 Example 1: 1418 >>> lst = ['b', 'c', 'a'] 1419 >>> it(lst).sorted_descending().to_list() 1420 ['c', 'b', 'a'] 1421 """ 1422 return self.sorted().reversed() 1423 1424 @overload 1425 def sorted_by_descending( 1426 self, key_selector: Callable[[T], SupportsRichComparisonT] 1427 ) -> Stream[T]: ... 1428 @overload 1429 def sorted_by_descending( 1430 self, key_selector: Callable[[T, int], SupportsRichComparisonT] 1431 ) -> Stream[T]: ... 1432 @overload 1433 def sorted_by_descending( 1434 self, key_selector: Callable[[T, int, Stream[T]], SupportsRichComparisonT] 1435 ) -> Stream[T]: ... 1436 def sorted_by_descending( 1437 self, key_selector: Callable[..., SupportsRichComparisonT] 1438 ) -> Stream[T]: 1439 """ 1440 Returns a sequence that yields elements of this sequence sorted descending according 1441 to natural sort order of the value returned by specified [key_selector] function. 1442 1443 Example 1: 1444 >>> lst = [ {'name': 'A', 'age': 12 }, {'name': 'C', 'age': 10 }, {'name': 'B', 'age': 11 } ] 1445 >>> it(lst).sorted_by_descending(lambda x: x['name']).to_list() 1446 [{'name': 'C', 'age': 10}, {'name': 'B', 'age': 11}, {'name': 'A', 'age': 12}] 1447 >>> it(lst).sorted_by_descending(lambda x: x['age']).to_list() 1448 [{'name': 'A', 'age': 12}, {'name': 'B', 'age': 11}, {'name': 'C', 'age': 10}] 1449 """ 1450 return self.sorted_by(key_selector).reversed() 1451 1452 # noinspection PyShadowingNames 1453 def sorted_with(self, comparator: Callable[[T, T], int]) -> Stream[T]: 1454 """ 1455 Returns a sequence that yields elements of this sequence sorted according to the specified [comparator]. 1456 1457 Example 1: 1458 >>> lst = ['aa', 'bbb', 'c'] 1459 >>> it(lst).sorted_with(lambda a, b: len(a)-len(b)).to_list() 1460 ['c', 'aa', 'bbb'] 1461 """ 1462 from functools import cmp_to_key 1463 1464 lst = list(self) 1465 lst.sort(key=cmp_to_key(comparator)) 1466 return it(lst) 1467 1468 @overload 1469 def associate(self, transform: Callable[[T], Tuple[K, V]]) -> Dict[K, V]: ... 1470 @overload 1471 def associate(self, transform: Callable[[T, int], Tuple[K, V]]) -> Dict[K, V]: ... 1472 @overload 1473 def associate(self, transform: Callable[[T, int, Stream[T]], Tuple[K, V]]) -> Dict[K, V]: ... 1474 def associate(self, transform: Callable[..., Tuple[K, V]]) -> Dict[K, V]: 1475 """ 1476 Returns a [Dict] containing key-value Tuple provided by [transform] function 1477 applied to elements of the given Stream. 1478 1479 Example 1: 1480 >>> lst = ['1', '2', '3'] 1481 >>> it(lst).associate(lambda x: (int(x), x)) 1482 {1: '1', 2: '2', 3: '3'} 1483 """ 1484 transform = self.__callback_overload_warpper__(transform) 1485 dic: Dict[K, V] = dict() 1486 for i in self: 1487 k, v = transform(i) 1488 dic[k] = v 1489 return dic 1490 1491 @overload 1492 def associate_by(self, key_selector: Callable[[T], K]) -> Dict[K, T]: ... 1493 @overload 1494 def associate_by(self, key_selector: Callable[[T, int], K]) -> Dict[K, T]: ... 1495 @overload 1496 def associate_by(self, key_selector: Callable[[T, int, Stream[T]], K]) -> Dict[K, T]: ... 1497 @overload 1498 def associate_by( 1499 self, key_selector: Callable[[T], K], value_transform: Callable[[T], V] 1500 ) -> Dict[K, V]: ... 1501 def associate_by( 1502 self, 1503 key_selector: Callable[..., K], 1504 value_transform: Optional[Callable[[T], V]] = None, 1505 ) -> Union[Dict[K, T], Dict[K, V]]: 1506 """ 1507 Returns a [Dict] containing key-value Tuple provided by [transform] function 1508 applied to elements of the given Stream. 1509 1510 Example 1: 1511 >>> lst = ['1', '2', '3'] 1512 >>> it(lst).associate_by(lambda x: int(x)) 1513 {1: '1', 2: '2', 3: '3'} 1514 1515 Example 2: 1516 >>> lst = ['1', '2', '3'] 1517 >>> it(lst).associate_by(lambda x: int(x), lambda x: x+x) 1518 {1: '11', 2: '22', 3: '33'} 1519 1520 """ 1521 key_selector = self.__callback_overload_warpper__(key_selector) 1522 1523 dic: Dict[K, Any] = dict() 1524 for i in self: 1525 k = key_selector(i) 1526 dic[k] = i if value_transform is None else value_transform(i) 1527 return dic 1528 1529 @overload 1530 def associate_by_to( 1531 self, destination: Dict[K, T], key_selector: Callable[[T], K] 1532 ) -> Dict[K, T]: ... 1533 @overload 1534 def associate_by_to( 1535 self, 1536 destination: Dict[K, V], 1537 key_selector: Callable[[T], K], 1538 value_transform: Callable[[T], V], 1539 ) -> Dict[K, V]: ... 1540 def associate_by_to( 1541 self, 1542 destination: Dict[K, Any], 1543 key_selector: Callable[[T], K], 1544 value_transform: Optional[Callable[[T], Any]] = None, 1545 ) -> Dict[K, Any]: 1546 """ 1547 Returns a [Dict] containing key-value Tuple provided by [transform] function 1548 applied to elements of the given Stream. 1549 1550 Example 1: 1551 >>> lst = ['1', '2', '3'] 1552 >>> it(lst).associate_by_to({}, lambda x: int(x)) 1553 {1: '1', 2: '2', 3: '3'} 1554 1555 Example 2: 1556 >>> lst = ['1', '2', '3'] 1557 >>> it(lst).associate_by_to({}, lambda x: int(x), lambda x: x+'!' ) 1558 {1: '1!', 2: '2!', 3: '3!'} 1559 1560 """ 1561 for i in self: 1562 k = key_selector(i) 1563 destination[k] = i if value_transform is None else value_transform(i) 1564 return destination 1565 1566 @overload 1567 def all(self, predicate: Callable[[T], bool]) -> bool: ... 1568 @overload 1569 def all(self, predicate: Callable[[T, int], bool]) -> bool: ... 1570 @overload 1571 def all(self, predicate: Callable[[T, int, Stream[T]], bool]) -> bool: ... 1572 def all(self, predicate: Callable[..., bool]) -> bool: 1573 """ 1574 Returns True if all elements of the Stream satisfy the specified [predicate] function. 1575 1576 Example 1: 1577 >>> lst = [1, 2, 3] 1578 >>> it(lst).all(lambda x: x > 0) 1579 True 1580 >>> it(lst).all(lambda x: x > 1) 1581 False 1582 """ 1583 predicate = self.__callback_overload_warpper__(predicate) 1584 for i in self: 1585 if not predicate(i): 1586 return False 1587 return True 1588 1589 @overload 1590 def any(self, predicate: Callable[[T], bool]) -> bool: ... 1591 @overload 1592 def any(self, predicate: Callable[[T, int], bool]) -> bool: ... 1593 @overload 1594 def any(self, predicate: Callable[[T, int, Stream[T]], bool]) -> bool: ... 1595 def any(self, predicate: Callable[..., bool]) -> bool: 1596 """ 1597 Returns True if any elements of the Stream satisfy the specified [predicate] function. 1598 1599 Example 1: 1600 >>> lst = [1, 2, 3] 1601 >>> it(lst).any(lambda x: x > 0) 1602 True 1603 >>> it(lst).any(lambda x: x > 3) 1604 False 1605 """ 1606 predicate = self.__callback_overload_warpper__(predicate) 1607 for i in self: 1608 if predicate(i): 1609 return True 1610 return False 1611 1612 @overload 1613 def count(self) -> int: ... 1614 @overload 1615 def count(self, predicate: Callable[[T], bool]) -> int: ... 1616 @overload 1617 def count(self, predicate: Callable[[T, int], bool]) -> int: ... 1618 @overload 1619 def count(self, predicate: Callable[[T, int, Stream[T]], bool]) -> int: ... 1620 def count(self, predicate: Optional[Callable[..., bool]] = None) -> int: 1621 """ 1622 Returns the number of elements in the Stream that satisfy the specified [predicate] function. 1623 1624 Example 1: 1625 >>> lst = [1, 2, 3] 1626 >>> it(lst).count() 1627 3 1628 >>> it(lst).count(lambda x: x > 0) 1629 3 1630 >>> it(lst).count(lambda x: x > 2) 1631 1 1632 """ 1633 if predicate is None: 1634 return len(self) 1635 predicate = self.__callback_overload_warpper__(predicate) 1636 return sum(1 for i in self if predicate(i)) 1637 1638 def contains(self, value: T) -> bool: 1639 """ 1640 Returns True if the Stream contains the specified [value]. 1641 1642 Example 1: 1643 >>> lst = [1, 2, 3] 1644 >>> it(lst).contains(1) 1645 True 1646 >>> it(lst).contains(4) 1647 False 1648 """ 1649 return value in self 1650 1651 def element_at(self, index: int) -> T: 1652 """ 1653 Returns the element at the specified [index] in the Stream. 1654 1655 Example 1: 1656 >>> lst = [1, 2, 3] 1657 >>> it(lst).element_at(1) 1658 2 1659 1660 Example 2: 1661 >>> lst = [1, 2, 3] 1662 >>> it(lst).element_at(3) 1663 Traceback (most recent call last): 1664 ... 1665 IndexError: Index 3 out of range 1666 """ 1667 return self.element_at_or_else( 1668 index, lambda index: throw(IndexError(f"Index {index} out of range")) 1669 ) 1670 1671 @overload 1672 def element_at_or_else(self, index: int) -> Optional[T]: 1673 """ 1674 Returns the element at the specified [index] in the Stream or the [default] value if the index is out of bounds. 1675 1676 Example 1: 1677 >>> lst = [1, 2, 3] 1678 >>> it(lst).element_at_or_else(1, 'default') 1679 2 1680 >>> it(lst).element_at_or_else(4, lambda x: 'default') 1681 'default' 1682 """ 1683 ... 1684 1685 @overload 1686 def element_at_or_else(self, index: int, default: T) -> T: ... 1687 @overload 1688 def element_at_or_else(self, index: int, default: Callable[[int], T]) -> T: ... 1689 def element_at_or_else( 1690 self, index: int, default: Union[Callable[[int], T], T, None] = None 1691 ) -> Optional[T]: 1692 """ 1693 Returns the element at the specified [index] in the Stream or the [default] value if the index is out of bounds. 1694 1695 Example 1: 1696 >>> lst = [1, 2, 3] 1697 >>> it(lst).element_at_or_else(1, lambda x: 'default') 1698 2 1699 >>> it(lst).element_at_or_else(4, lambda x: 'default') 1700 'default' 1701 1702 """ 1703 if index >= 0: 1704 if ( 1705 isinstance(self.__transform__, NonTransform) 1706 and isinstance(self.__transform__.iter, list) 1707 and index < len(self.__transform__.iter) 1708 ): 1709 return self.__transform__.iter[index] 1710 for i, e in enumerate(self): 1711 if i == index: 1712 return e 1713 return default(index) if callable(default) else default # type: ignore 1714 1715 def element_at_or_default(self, index: int, default: T) -> T: 1716 """ 1717 Returns the element at the specified [index] in the Stream or the [default] value if the index is out of bounds. 1718 1719 Example 1: 1720 >>> lst = [1, 2, 3] 1721 >>> it(lst).element_at_or_default(1, 'default') 1722 2 1723 >>> it(lst).element_at_or_default(4, 'default') 1724 'default' 1725 1726 """ 1727 return self.element_at_or_else(index, default) 1728 1729 def element_at_or_none(self, index: int) -> Optional[T]: 1730 """ 1731 Returns the element at the specified [index] in the Stream or None if the index is out of bounds. 1732 1733 Example 1: 1734 >>> lst = [1, 2, 3] 1735 >>> it(lst).element_at_or_none(1) 1736 2 1737 >>> it(lst).element_at_or_none(4) is None 1738 True 1739 """ 1740 return self.element_at_or_else(index) 1741 1742 def distinct(self) -> Stream[T]: 1743 """ 1744 Returns a new Stream containing the distinct elements of the given Stream. 1745 1746 Example 1: 1747 >>> lst = [1, 2, 3, 1, 2, 3] 1748 >>> it(lst).distinct().to_list() 1749 [1, 2, 3] 1750 1751 Example 2: 1752 >>> lst = [(1, 'A'), (1, 'A'), (1, 'A'), (2, 'A'), (3, 'C'), (3, 'D')] 1753 >>> it(lst).distinct().sorted().to_list() 1754 [(1, 'A'), (2, 'A'), (3, 'C'), (3, 'D')] 1755 1756 """ 1757 from .distinct import DistinctTransform 1758 1759 return it(DistinctTransform(self)) 1760 1761 @overload 1762 def distinct_by(self, key_selector: Callable[[T], Any]) -> Stream[T]: ... 1763 @overload 1764 def distinct_by(self, key_selector: Callable[[T, int], Any]) -> Stream[T]: ... 1765 @overload 1766 def distinct_by(self, key_selector: Callable[[T, int, Stream[T]], Any]) -> Stream[T]: ... 1767 def distinct_by(self, key_selector: Callable[..., Any]) -> Stream[T]: 1768 """ 1769 Returns a new Stream containing the distinct elements of the given Stream. 1770 1771 Example 1: 1772 >>> lst = [1, 2, 3, 1, 2, 3] 1773 >>> it(lst).distinct_by(lambda x: x%2).to_list() 1774 [1, 2] 1775 """ 1776 from .distinct import DistinctTransform 1777 1778 return it(DistinctTransform(self, self.__callback_overload_warpper__(key_selector))) 1779 1780 @overload 1781 def reduce(self, accumulator: Callable[[T, T], T]) -> T: ... 1782 @overload 1783 def reduce(self, accumulator: Callable[[U, T], U], initial: U) -> U: ... 1784 def reduce(self, accumulator: Callable[..., U], initial: Optional[U] = None) -> Optional[U]: 1785 """ 1786 Returns the result of applying the specified [accumulator] function to the given Stream's elements. 1787 1788 Example 1: 1789 >>> lst = [1, 2, 3] 1790 >>> it(lst).reduce(lambda x, y: x+y) 1791 6 1792 """ 1793 result: Optional[U] = initial 1794 for i, e in enumerate(self): 1795 if i == 0 and initial is None: 1796 result = e # type: ignore 1797 continue 1798 1799 result = accumulator(result, e) 1800 return result 1801 1802 def fold(self, initial: U, accumulator: Callable[[U, T], U]) -> U: 1803 """ 1804 Returns the result of applying the specified [accumulator] function to the given Stream's elements. 1805 1806 Example 1: 1807 >>> lst = [1, 2, 3] 1808 >>> it(lst).fold(0, lambda x, y: x+y) 1809 6 1810 """ 1811 return self.reduce(accumulator, initial) 1812 1813 @overload 1814 def sum_of(self, selector: Callable[[T], int]) -> int: ... 1815 @overload 1816 def sum_of(self, selector: Callable[[T], float]) -> float: ... 1817 def sum_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]: 1818 """ 1819 Returns the sum of the elements of the given Stream. 1820 1821 Example 1: 1822 >>> lst = [1, 2, 3] 1823 >>> it(lst).sum_of(lambda x: x) 1824 6 1825 """ 1826 return sum(selector(i) for i in self) 1827 1828 @overload 1829 def max_of(self, selector: Callable[[T], int]) -> int: ... 1830 @overload 1831 def max_of(self, selector: Callable[[T], float]) -> float: ... 1832 def max_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]: 1833 """ 1834 Returns the maximum element of the given Stream. 1835 1836 Example 1: 1837 >>> lst = [1, 2, 3] 1838 >>> it(lst).max_of(lambda x: x) 1839 3 1840 """ 1841 return max(selector(i) for i in self) 1842 1843 @overload 1844 def max_by_or_none(self, selector: Callable[[T], int]) -> Optional[T]: ... 1845 @overload 1846 def max_by_or_none(self, selector: Callable[[T], float]) -> Optional[T]: ... 1847 def max_by_or_none(self, selector: Callable[[T], Union[float, int]]) -> Optional[T]: 1848 """ 1849 Returns the first element yielding the largest value of the given function 1850 or `none` if there are no elements. 1851 1852 Example 1: 1853 >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }] 1854 >>> it(lst).max_by_or_none(lambda x: x["num"]) 1855 {'name': 'B', 'num': 200} 1856 1857 Example 2: 1858 >>> lst = [] 1859 >>> it(lst).max_by_or_none(lambda x: x["num"]) 1860 """ 1861 1862 max_item = None 1863 max_val = None 1864 1865 for item in self: 1866 val = selector(item) 1867 if max_val is None or val > max_val: 1868 max_item = item 1869 max_val = val 1870 1871 return max_item 1872 1873 @overload 1874 def max_by(self, selector: Callable[[T], int]) -> T: ... 1875 @overload 1876 def max_by(self, selector: Callable[[T], float]) -> T: ... 1877 def max_by(self, selector: Callable[[T], Union[float, int]]) -> T: 1878 """ 1879 Returns the first element yielding the largest value of the given function. 1880 1881 Example 1: 1882 >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }] 1883 >>> it(lst).max_by(lambda x: x["num"]) 1884 {'name': 'B', 'num': 200} 1885 1886 Exmaple 2: 1887 >>> lst = [] 1888 >>> it(lst).max_by(lambda x: x["num"]) 1889 Traceback (most recent call last): 1890 ... 1891 ValueError: Stream is empty. 1892 """ 1893 max_item = self.max_by_or_none(selector) 1894 if max_item is None: 1895 raise ValueError("Stream is empty.") 1896 return max_item 1897 1898 @overload 1899 def min_of(self, selector: Callable[[T], int]) -> int: 1900 """ 1901 Returns the minimum element of the given Stream. 1902 1903 Example 1: 1904 >>> lst = [1, 2, 3] 1905 >>> it(lst).min_of(lambda x: x) 1906 1 1907 """ 1908 ... 1909 1910 @overload 1911 def min_of(self, selector: Callable[[T], float]) -> float: ... 1912 def min_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]: 1913 return min(selector(i) for i in self) 1914 1915 @overload 1916 def min_by_or_none(self, selector: Callable[[T], int]) -> Optional[T]: ... 1917 @overload 1918 def min_by_or_none(self, selector: Callable[[T], float]) -> Optional[T]: ... 1919 def min_by_or_none(self, selector: Callable[[T], float]) -> Optional[T]: 1920 """ 1921 Returns the first element yielding the smallest value of the given function 1922 or `none` if there are no elements. 1923 1924 Example 1: 1925 >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }] 1926 >>> it(lst).min_by_or_none(lambda x: x["num"]) 1927 {'name': 'A', 'num': 100} 1928 1929 Exmaple 2: 1930 >>> lst = [] 1931 >>> it(lst).min_by_or_none(lambda x: x["num"]) 1932 """ 1933 min_item = None 1934 min_val = None 1935 1936 for item in self: 1937 val = selector(item) 1938 if min_val is None or val < min_val: 1939 min_item = item 1940 min_val = val 1941 1942 return min_item 1943 1944 @overload 1945 def min_by(self, selector: Callable[[T], int]) -> T: ... 1946 @overload 1947 def min_by(self, selector: Callable[[T], float]) -> T: ... 1948 def min_by(self, selector: Callable[[T], float]) -> T: 1949 """ 1950 Returns the first element yielding the smallest value of the given function. 1951 1952 Example 1: 1953 >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }] 1954 >>> it(lst).min_by(lambda x: x["num"]) 1955 {'name': 'A', 'num': 100} 1956 1957 Exmaple 2: 1958 >>> lst = [] 1959 >>> it(lst).min_by(lambda x: x["num"]) 1960 Traceback (most recent call last): 1961 ... 1962 ValueError: Stream is empty. 1963 """ 1964 min_item = self.min_by_or_none(selector) 1965 if min_item is None: 1966 raise ValueError("Stream is empty.") 1967 1968 return min_item 1969 1970 def mean_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]: 1971 """ 1972 Returns the mean of the elements of the given Stream. 1973 1974 Example 1: 1975 >>> lst = [1, 2, 3] 1976 >>> it(lst).mean_of(lambda x: x) 1977 2.0 1978 """ 1979 return self.sum_of(selector) / len(self) 1980 1981 @overload 1982 def sum(self: Stream[int]) -> int: 1983 """ 1984 Returns the sum of the elements of the given Stream. 1985 1986 Example 1: 1987 >>> lst = [1, 2, 3] 1988 >>> it(lst).sum() 1989 6 1990 """ 1991 ... 1992 1993 @overload 1994 def sum(self: Stream[float]) -> float: ... 1995 def sum(self: Union[Stream[int], Stream[float]]) -> Union[float, int]: 1996 """ 1997 Returns the sum of the elements of the given Stream. 1998 1999 Example 1: 2000 >>> lst = [1, 2, 3] 2001 >>> it(lst).sum() 2002 6 2003 """ 2004 return sum(self) 2005 2006 @overload 2007 def max(self: Stream[int]) -> int: ... 2008 @overload 2009 def max(self: Stream[float]) -> float: ... 2010 def max(self: Union[Stream[int], Stream[float]]) -> Union[float, int]: 2011 """ 2012 Returns the maximum element of the given Stream. 2013 2014 Example 1: 2015 >>> lst = [1, 2, 3] 2016 >>> it(lst).max() 2017 3 2018 """ 2019 return max(self) 2020 2021 @overload 2022 def max_or_default(self: Stream[int]) -> int: ... 2023 @overload 2024 def max_or_default(self: Stream[int], default: V) -> Union[int, V]: ... 2025 @overload 2026 def max_or_default(self: Stream[float]) -> float: ... 2027 @overload 2028 def max_or_default(self: Stream[float], default: V) -> Union[float, V]: ... 2029 def max_or_default( 2030 self: Union[Stream[int], Stream[float]], default: Optional[V] = None 2031 ) -> Union[float, int, V, None]: 2032 """ 2033 Returns the maximum element of the given Stream. 2034 2035 Example 1: 2036 >>> lst = [1, 2, 3] 2037 >>> it(lst).max_or_default() 2038 3 2039 2040 Example 2: 2041 >>> lst = [] 2042 >>> it(lst).max_or_default() is None 2043 True 2044 2045 Example 3: 2046 >>> lst = [] 2047 >>> it(lst).max_or_default(9) 2048 9 2049 """ 2050 if self.is_empty(): 2051 return default 2052 return max(self) 2053 2054 @overload 2055 def max_or_none(self: Stream[int]) -> int: ... 2056 @overload 2057 def max_or_none(self: Stream[float]) -> float: ... 2058 def max_or_none( 2059 self: Union[Stream[int], Stream[float]], 2060 ) -> Union[float, int, None]: 2061 """ 2062 Returns the maximum element of the given Stream. 2063 2064 Example 1: 2065 >>> lst = [1, 2, 3] 2066 >>> it(lst).max_or_none() 2067 3 2068 2069 Example 2: 2070 >>> lst = [] 2071 >>> it(lst).max_or_none() is None 2072 True 2073 """ 2074 return self.max_or_default(None) 2075 2076 @overload 2077 def min(self: Stream[int]) -> int: 2078 """ 2079 Returns the minimum element of the given Stream. 2080 2081 Example 1: 2082 >>> lst = [1, 2, 3] 2083 >>> it(lst).min() 2084 1 2085 """ 2086 ... 2087 2088 @overload 2089 def min(self: Stream[float]) -> float: ... 2090 def min(self: Union[Stream[int], Stream[float]]) -> Union[float, int]: 2091 """ 2092 Returns the minimum element of the given Stream. 2093 2094 Example 1: 2095 >>> lst = [1, 2, 3] 2096 >>> it(lst).min() 2097 1 2098 """ 2099 return min(self) 2100 2101 @overload 2102 def min_or_none(self: Stream[int]) -> Optional[int]: 2103 """ 2104 Returns the minimum element of the given Stream. 2105 2106 Example 1: 2107 >>> lst = [1, 2, 3] 2108 >>> it(lst).min_or_none() 2109 1 2110 """ 2111 ... 2112 2113 @overload 2114 def min_or_none(self: Stream[float]) -> Optional[float]: ... 2115 def min_or_none( 2116 self: Union[Stream[int], Stream[float]], 2117 ) -> Union[float, int, None]: 2118 """ 2119 Returns the minimum element of the given Stream. 2120 2121 Example 1: 2122 >>> lst = [1, 2, 3] 2123 >>> it(lst).min_or_none() 2124 1 2125 """ 2126 return self.min_or_default(None) 2127 2128 @overload 2129 def min_or_default(self: Stream[int]) -> int: 2130 """ 2131 Returns the minimum element of the given Stream. 2132 2133 Example 1: 2134 >>> lst = [1, 2, 3] 2135 >>> it(lst).min_or_default() 2136 1 2137 """ 2138 ... 2139 2140 @overload 2141 def min_or_default(self: Stream[int], default: V) -> Union[int, V]: ... 2142 @overload 2143 def min_or_default(self: Stream[float]) -> float: ... 2144 @overload 2145 def min_or_default(self: Stream[float], default: V) -> Union[float, V]: ... 2146 def min_or_default( 2147 self: Union[Stream[int], Stream[float]], default: Optional[V] = None 2148 ) -> Union[float, int, V, None]: 2149 """ 2150 Returns the minimum element of the given Stream. 2151 2152 Example 1: 2153 >>> lst = [1, 2, 3] 2154 >>> it(lst).min_or_default() 2155 1 2156 2157 Example 2: 2158 >>> lst = [] 2159 >>> it(lst).min_or_default(9) 2160 9 2161 """ 2162 if self.is_empty(): 2163 return default 2164 return min(self) 2165 2166 @overload 2167 def mean(self: Stream[int]) -> float: 2168 """ 2169 Returns the mean of the elements of the given Stream. 2170 2171 Example 1: 2172 >>> lst = [1, 2, 3] 2173 >>> it(lst).mean() 2174 2.0 2175 """ 2176 ... 2177 2178 @overload 2179 def mean(self: Stream[float]) -> float: ... 2180 def mean(self: Union[Stream[int], Stream[float]]) -> float: 2181 """ 2182 Returns the mean of the elements of the given Stream. 2183 2184 Example 1: 2185 >>> lst = [1, 2, 3] 2186 >>> it(lst).mean() 2187 2.0 2188 """ 2189 return self.sum() / len(self) 2190 2191 # noinspection PyShadowingNames 2192 def reversed(self) -> Stream[T]: 2193 """ 2194 Returns a list with elements in reversed order. 2195 2196 Example 1: 2197 >>> lst = ['b', 'c', 'a'] 2198 >>> it(lst).reversed().to_list() 2199 ['a', 'c', 'b'] 2200 """ 2201 lst = list(self) 2202 lst.reverse() 2203 return it(lst) 2204 2205 @overload 2206 def flat_map(self, transform: Callable[[T], Iterable[U]]) -> Stream[U]: ... 2207 @overload 2208 def flat_map(self, transform: Callable[[T, int], Iterable[U]]) -> Stream[U]: ... 2209 @overload 2210 def flat_map(self, transform: Callable[[T, int, Stream[T]], Iterable[U]]) -> Stream[U]: ... 2211 def flat_map(self, transform: Callable[..., Iterable[U]]) -> Stream[U]: 2212 """ 2213 Returns a single list of all elements yielded from results of [transform] 2214 function being invoked on each element of original collection. 2215 2216 Example 1: 2217 >>> lst = [['a', 'b'], ['c'], ['d', 'e']] 2218 >>> it(lst).flat_map(lambda x: x).to_list() 2219 ['a', 'b', 'c', 'd', 'e'] 2220 """ 2221 return self.map(transform).flatten() 2222 2223 def flatten(self: Iterable[Iterable[U]]) -> Stream[U]: 2224 """ 2225 Returns a sequence of all elements from all sequences in this sequence. 2226 2227 Example 1: 2228 >>> lst = [['a', 'b'], ['c'], ['d', 'e']] 2229 >>> it(lst).flatten().to_list() 2230 ['a', 'b', 'c', 'd', 'e'] 2231 """ 2232 from .flattening import FlatteningTransform 2233 2234 return it(FlatteningTransform(self)) 2235 2236 @overload 2237 def group_by(self, key_selector: Callable[[T], K]) -> Stream[Grouping[K, T]]: ... 2238 @overload 2239 def group_by(self, key_selector: Callable[[T, int], K]) -> Stream[Grouping[K, T]]: ... 2240 @overload 2241 def group_by( 2242 self, key_selector: Callable[[T, int, Stream[T]], K] 2243 ) -> Stream[Grouping[K, T]]: ... 2244 def group_by(self, key_selector: Callable[..., K]) -> Stream[Grouping[K, T]]: 2245 """ 2246 Returns a dictionary with keys being the result of [key_selector] function being invoked on each element of original collection 2247 and values being the corresponding elements of original collection. 2248 2249 Example 1: 2250 >>> lst = [1, 2, 3, 4, 5] 2251 >>> it(lst).group_by(lambda x: x%2).map(lambda x: (x.key, x.values.to_list())).to_list() 2252 [(1, [1, 3, 5]), (0, [2, 4])] 2253 """ 2254 from .grouping import GroupingTransform 2255 2256 return it(GroupingTransform(self, self.__callback_overload_warpper__(key_selector))) 2257 2258 @overload 2259 def group_by_to( 2260 self, destination: Dict[K, List[T]], key_selector: Callable[[T], K] 2261 ) -> Dict[K, List[T]]: ... 2262 @overload 2263 def group_by_to( 2264 self, destination: Dict[K, List[T]], key_selector: Callable[[T, int], K] 2265 ) -> Dict[K, List[T]]: ... 2266 @overload 2267 def group_by_to( 2268 self, 2269 destination: Dict[K, List[T]], 2270 key_selector: Callable[[T, int, Stream[T]], K], 2271 ) -> Dict[K, List[T]]: ... 2272 def group_by_to( 2273 self, destination: Dict[K, List[T]], key_selector: Callable[..., K] 2274 ) -> Dict[K, List[T]]: 2275 """ 2276 Returns a dictionary with keys being the result of [key_selector] function being invoked on each element of original collection 2277 and values being the corresponding elements of original collection. 2278 2279 Example 1: 2280 >>> lst = [1, 2, 3, 4, 5] 2281 >>> it(lst).group_by_to({}, lambda x: x%2) 2282 {1: [1, 3, 5], 0: [2, 4]} 2283 """ 2284 key_selector = self.__callback_overload_warpper__(key_selector) 2285 for e in self: 2286 k = key_selector(e) 2287 if k not in destination: 2288 destination[k] = [] 2289 destination[k].append(e) 2290 return destination 2291 2292 @overload 2293 def for_each(self, action: Callable[[T], None]) -> None: ... 2294 @overload 2295 def for_each(self, action: Callable[[T, int], None]) -> None: ... 2296 @overload 2297 def for_each(self, action: Callable[[T, int, Stream[T]], None]) -> None: ... 2298 def for_each(self, action: Callable[..., None]) -> None: 2299 """ 2300 Invokes [action] function on each element of the given Stream. 2301 2302 Example 1: 2303 >>> lst = ['a', 'b', 'c'] 2304 >>> it(lst).for_each(lambda x: print(x)) 2305 a 2306 b 2307 c 2308 2309 Example 2: 2310 >>> lst = ['a', 'b', 'c'] 2311 >>> it(lst).for_each(lambda x, i: print(x, i)) 2312 a 0 2313 b 1 2314 c 2 2315 """ 2316 self.on_each(action) 2317 2318 @overload 2319 def parallel_for_each( 2320 self, action: Callable[[T], None], max_workers: Optional[int] = None 2321 ) -> None: ... 2322 @overload 2323 def parallel_for_each( 2324 self, action: Callable[[T, int], None], max_workers: Optional[int] = None 2325 ) -> None: ... 2326 @overload 2327 def parallel_for_each( 2328 self, 2329 action: Callable[[T, int, Stream[T]], None], 2330 max_workers: Optional[int] = None, 2331 ) -> None: ... 2332 def parallel_for_each( 2333 self, action: Callable[..., None], max_workers: Optional[int] = None 2334 ) -> None: 2335 """ 2336 Invokes [action] function on each element of the given Stream in parallel. 2337 2338 Example 1: 2339 >>> lst = ['a', 'b', 'c'] 2340 >>> it(lst).parallel_for_each(lambda x: print(x)) 2341 a 2342 b 2343 c 2344 2345 Example 2: 2346 >>> lst = ['a', 'b', 'c'] 2347 >>> it(lst).parallel_for_each(lambda x: print(x), max_workers=2) 2348 a 2349 b 2350 c 2351 """ 2352 self.parallel_on_each(action, max_workers) 2353 2354 @overload 2355 def on_each(self, action: Callable[[T], None]) -> Stream[T]: ... 2356 @overload 2357 def on_each(self, action: Callable[[T, int], None]) -> Stream[T]: ... 2358 @overload 2359 def on_each(self, action: Callable[[T, int, Stream[T]], None]) -> Stream[T]: ... 2360 def on_each(self, action: Callable[..., None]) -> Stream[T]: 2361 """ 2362 Invokes [action] function on each element of the given Stream. 2363 2364 Example 1: 2365 >>> lst = ['a', 'b', 'c'] 2366 >>> it(lst).on_each(lambda x: print(x)) and None 2367 a 2368 b 2369 c 2370 2371 Example 2: 2372 >>> lst = ['a', 'b', 'c'] 2373 >>> it(lst).on_each(lambda x, i: print(x, i)) and None 2374 a 0 2375 b 1 2376 c 2 2377 """ 2378 action = self.__callback_overload_warpper__(action) 2379 for i in self: 2380 action(i) 2381 return self 2382 2383 @overload 2384 def parallel_on_each( 2385 self, 2386 action: Callable[[T], None], 2387 max_workers: Optional[int] = None, 2388 chunksize: int = 1, 2389 executor: "ParallelMappingTransform.Executor" = "Thread", 2390 ) -> Stream[T]: ... 2391 @overload 2392 def parallel_on_each( 2393 self, 2394 action: Callable[[T, int], None], 2395 max_workers: Optional[int] = None, 2396 chunksize: int = 1, 2397 executor: "ParallelMappingTransform.Executor" = "Thread", 2398 ) -> Stream[T]: ... 2399 @overload 2400 def parallel_on_each( 2401 self, 2402 action: Callable[[T, int, Stream[T]], None], 2403 max_workers: Optional[int] = None, 2404 chunksize: int = 1, 2405 executor: "ParallelMappingTransform.Executor" = "Thread", 2406 ) -> Stream[T]: ... 2407 def parallel_on_each( 2408 self, 2409 action: Callable[..., None], 2410 max_workers: Optional[int] = None, 2411 chunksize: int = 1, 2412 executor: "ParallelMappingTransform.Executor" = "Thread", 2413 ) -> Stream[T]: 2414 """ 2415 Invokes [action] function on each element of the given Stream. 2416 2417 Example 1: 2418 >>> lst = ['a', 'b', 'c'] 2419 >>> it(lst).parallel_on_each(lambda x: print(x)) and None 2420 a 2421 b 2422 c 2423 2424 Example 2: 2425 >>> lst = ['a', 'b', 'c'] 2426 >>> it(lst).parallel_on_each(lambda x: print(x), max_workers=2) and None 2427 a 2428 b 2429 c 2430 """ 2431 from .parallel_mapping import ParallelMappingTransform 2432 2433 action = self.__callback_overload_warpper__(action) 2434 for _ in ParallelMappingTransform(self, action, max_workers, chunksize, executor): 2435 pass 2436 return self 2437 2438 @overload 2439 def zip(self, other: Iterable[U]) -> Stream[Tuple[T, U]]: ... 2440 @overload 2441 def zip(self, other: Iterable[U], transform: Callable[[T, U], V]) -> Stream[V]: ... 2442 def zip( 2443 self, 2444 other: Iterable[Any], 2445 transform: Optional[Callable[..., V]] = None, # type: ignore 2446 ) -> Stream[Any]: 2447 """ 2448 Returns a new Stream of tuples, where each tuple contains two elements. 2449 2450 Example 1: 2451 >>> lst1 = ['a', 'b', 'c'] 2452 >>> lst2 = [1, 2, 3] 2453 >>> it(lst1).zip(lst2).to_list() 2454 [('a', 1), ('b', 2), ('c', 3)] 2455 2456 Example 2: 2457 >>> lst1 = ['a', 'b', 'c'] 2458 >>> lst2 = [1, 2, 3] 2459 >>> it(lst1).zip(lst2, lambda x, y: x + '__' +str( y)).to_list() 2460 ['a__1', 'b__2', 'c__3'] 2461 """ 2462 if transform is None: 2463 2464 def transform(*x: Any) -> Tuple[Any, ...]: 2465 return (*x,) 2466 2467 from .merging import MergingTransform 2468 2469 return it(MergingTransform(self, other, transform)) 2470 2471 @overload 2472 def zip_with_next(self) -> Stream[Tuple[T, T]]: ... 2473 @overload 2474 def zip_with_next(self, transform: Callable[[T, T], V]) -> Stream[V]: ... 2475 def zip_with_next(self, transform: Optional[Callable[[T, T], Any]] = None) -> Stream[Any]: 2476 """ 2477 Returns a sequence containing the results of applying the given [transform] function 2478 to an each pair of two adjacent elements in this sequence. 2479 2480 Example 1: 2481 >>> lst = ['a', 'b', 'c'] 2482 >>> it(lst).zip_with_next(lambda x, y: x + '__' + y).to_list() 2483 ['a__b', 'b__c'] 2484 2485 Example 2: 2486 >>> lst = ['a', 'b', 'c'] 2487 >>> it(lst).zip_with_next().to_list() 2488 [('a', 'b'), ('b', 'c')] 2489 """ 2490 from .merging_with_next import MergingWithNextTransform 2491 2492 return it(MergingWithNextTransform(self, transform or (lambda a, b: (a, b)))) 2493 2494 @overload 2495 def unzip(self: Stream[Tuple[U, V]]) -> "Tuple[ListLike[U], ListLike[V]]": ... 2496 @overload 2497 def unzip(self, transform: Callable[[T], Tuple[U, V]]) -> "Tuple[ListLike[U], ListLike[V]]": ... 2498 @overload 2499 def unzip( 2500 self, transform: Callable[[T, int], Tuple[U, V]] 2501 ) -> "Tuple[ListLike[U], ListLike[V]]": ... 2502 @overload 2503 def unzip( 2504 self, transform: Callable[[T, int, Stream[T]], Tuple[U, V]] 2505 ) -> "Tuple[ListLike[U], ListLike[V]]": ... 2506 def unzip( # type: ignore 2507 self: Stream[Tuple[U, V]], 2508 transform: Union[Optional[Callable[..., Tuple[Any, Any]]], bool] = None, 2509 ) -> "Tuple[ListLike[U], ListLike[V]]": 2510 """ 2511 Returns a pair of lists, where first list is built from the first values of each pair from this array, second list is built from the second values of each pair from this array. 2512 2513 Example 1: 2514 >>> lst = [{'name': 'a', 'age': 11}, {'name': 'b', 'age': 12}, {'name': 'c', 'age': 13}] 2515 >>> a, b = it(lst).unzip(lambda x: (x['name'], x['age'])) 2516 >>> a 2517 ['a', 'b', 'c'] 2518 >>> b 2519 [11, 12, 13] 2520 2521 Example 1: 2522 >>> lst = [('a', 11), ('b', 12), ('c', 13)] 2523 >>> a, b = it(lst).unzip() 2524 >>> a 2525 ['a', 'b', 'c'] 2526 >>> b 2527 [11, 12, 13] 2528 """ 2529 from .list_like import ListLike 2530 2531 it = self 2532 if isinstance(transform, bool): 2533 transform = None 2534 2535 if transform is not None: 2536 transform = self.__callback_overload_warpper__(transform) 2537 it = it.map(transform) 2538 2539 a = it.map(lambda x: x[0]) # type: ignore 2540 b = it.map(lambda x: x[1]) # type: ignore 2541 2542 return ListLike(a), ListLike(b) 2543 2544 def with_index(self) -> Stream[IndexedValue[T]]: 2545 """ 2546 Returns a sequence containing the elements of this sequence and their indexes. 2547 2548 Example 1: 2549 >>> lst = ['a', 'b', 'c'] 2550 >>> it(lst).with_index().to_list() 2551 [IndexedValue(0, a), IndexedValue(1, b), IndexedValue(2, c)] 2552 """ 2553 return self.indexed() 2554 2555 @overload 2556 def shuffled(self) -> Stream[T]: ... 2557 @overload 2558 def shuffled(self, seed: Union[int, float, str, bytes, bytearray, None]) -> Stream[T]: ... 2559 @overload 2560 def shuffled(self, random: "Random") -> Stream[T]: ... 2561 def shuffled( # type: ignore 2562 self, seed: Union["Random", int, float, str, bytes, bytearray, None] = None 2563 ) -> Stream[T]: 2564 """ 2565 Returns a sequence that yields elements of this sequence randomly shuffled 2566 using the specified [random] instance as the source of randomness. 2567 2568 Example 1: 2569 >>> lst = ['a', 'b', 'c'] 2570 >>> it(lst).shuffled('123').to_list() 2571 ['b', 'a', 'c'] 2572 2573 Example 2: 2574 >>> from random import Random 2575 >>> lst = ['a', 'b', 'c'] 2576 >>> it(lst).shuffled(Random('123')).to_list() 2577 ['b', 'a', 'c'] 2578 2579 Example 3: 2580 >>> lst = ['a', 'b', 'c'] 2581 >>> it(lst).shuffled(123).to_list() 2582 ['c', 'b', 'a'] 2583 """ 2584 from .shuffling import ShufflingTransform 2585 2586 return it(ShufflingTransform(self, seed)) 2587 2588 @overload 2589 def partition(self, predicate: Callable[[T], bool]) -> "Tuple[ListLike[T], ListLike[T]]": ... 2590 @overload 2591 def partition( 2592 self, predicate: Callable[[T, int], bool] 2593 ) -> "Tuple[ListLike[T], ListLike[T]]": ... 2594 @overload 2595 def partition( 2596 self, predicate: Callable[[T, int, Stream[T]], bool] 2597 ) -> "Tuple[ListLike[T], ListLike[T]]": ... 2598 def partition(self, predicate: Callable[..., bool]) -> "Tuple[ListLike[T], ListLike[T]]": 2599 """ 2600 Partitions the elements of the given Stream into two groups, 2601 the first group containing the elements for which the predicate returns true, 2602 and the second containing the rest. 2603 2604 Example 1: 2605 >>> lst = ['a', 'b', 'c', '2'] 2606 >>> it(lst).partition(lambda x: x.isalpha()) 2607 (['a', 'b', 'c'], ['2']) 2608 2609 Example 2: 2610 >>> lst = ['a', 'b', 'c', '2'] 2611 >>> it(lst).partition(lambda _, i: i % 2 == 0) 2612 (['a', 'c'], ['b', '2']) 2613 """ 2614 from .list_like import ListLike 2615 2616 predicate_a = self.__callback_overload_warpper__(predicate) 2617 predicate_b = self.__callback_overload_warpper__(predicate) 2618 part_a = self.filter(predicate_a) 2619 part_b = self.filter(lambda x: not predicate_b(x)) 2620 return ListLike(part_a), ListLike(part_b) 2621 2622 def indexed(self) -> Stream[IndexedValue[T]]: 2623 return self.map(lambda x, i: IndexedValue(x, i)) 2624 2625 @overload 2626 def combinations(self, n: Literal[2]) -> Stream[Tuple[T, T]]: ... 2627 @overload 2628 def combinations(self, n: Literal[3]) -> Stream[Tuple[T, T, T]]: ... 2629 @overload 2630 def combinations(self, n: Literal[4]) -> Stream[Tuple[T, T, T, T]]: ... 2631 @overload 2632 def combinations(self, n: Literal[5]) -> Stream[Tuple[T, T, T, T, T]]: ... 2633 def combinations(self, n: int) -> Stream[Tuple[T, ...]]: 2634 """ 2635 Returns a Stream of all possible combinations of size [n] from the given Stream. 2636 2637 Example 1: 2638 >>> lst = ['a', 'b', 'c'] 2639 >>> it(lst).combinations(2).to_list() 2640 [('a', 'b'), ('a', 'c'), ('b', 'c')] 2641 """ 2642 from .combination import CombinationTransform 2643 2644 return it(CombinationTransform(self, n)) 2645 2646 def nth(self, n: int) -> T: 2647 """ 2648 Returns the nth element of the given Stream. 2649 2650 Example 1: 2651 >>> lst = ['a', 'b', 'c'] 2652 >>> it(lst).nth(2) 2653 'c' 2654 """ 2655 return self.skip(n).first() 2656 2657 def windowed(self, size: int, step: int = 1, partialWindows: bool = False) -> Stream[List[T]]: 2658 """ 2659 Returns a Stream of all possible sliding windows of size [size] from the given Stream. 2660 2661 Example 1: 2662 >>> lst = ['a', 'b', 'c', 'd', 'e'] 2663 >>> it(lst).windowed(3).to_list() 2664 [['a', 'b', 'c'], ['b', 'c', 'd'], ['c', 'd', 'e']] 2665 2666 Example 2: 2667 >>> lst = ['a', 'b', 'c', 'd', 'e'] 2668 >>> it(lst).windowed(3, 2).to_list() 2669 [['a', 'b', 'c'], ['c', 'd', 'e']] 2670 2671 Example 3: 2672 >>> lst = ['a', 'b', 'c', 'd', 'e', 'f'] 2673 >>> it(lst).windowed(3, 2, True).to_list() 2674 [['a', 'b', 'c'], ['c', 'd', 'e'], ['e', 'f']] 2675 """ 2676 from .windowed import WindowedTransform 2677 2678 return it(WindowedTransform(self, size, step, partialWindows)) 2679 2680 def chunked(self, size: int) -> Stream[List[T]]: 2681 """ 2682 Returns a Stream of all possible chunks of size [size] from the given Stream. 2683 2684 Example 1: 2685 >>> lst = ['a', 'b', 'c', 'd', 'e'] 2686 >>> it(lst).chunked(3).to_list() 2687 [['a', 'b', 'c'], ['d', 'e']] 2688 2689 2690 Example 2: 2691 >>> lst = ['a', 'b', 'c', 'd', 'e', 'f'] 2692 >>> it(lst).chunked(3).to_list() 2693 [['a', 'b', 'c'], ['d', 'e', 'f']] 2694 """ 2695 return self.windowed(size, size, True) 2696 2697 def repeat(self, n: int) -> Stream[T]: 2698 """ 2699 Returns a Stream containing this sequence repeated n times. 2700 2701 Example 1: 2702 >>> lst = ['a', 'b'] 2703 >>> it(lst).repeat(3).to_list() 2704 ['a', 'b', 'a', 'b', 'a', 'b'] 2705 """ 2706 from .concat import ConcatTransform 2707 2708 return it(ConcatTransform([self] * n)) 2709 2710 def concat(self, *other: Iterable[T]) -> Stream[T]: 2711 """ 2712 Returns a Stream of all elements of the given Stream, followed by all elements of the given Stream. 2713 2714 Example 1: 2715 >>> lst1 = ['a', 'b', 'c'] 2716 >>> lst2 = [1, 2, 3] 2717 >>> it(lst1).concat(lst2).to_list() 2718 ['a', 'b', 'c', 1, 2, 3] 2719 2720 Example 2: 2721 >>> lst1 = ['a', 'b', 'c'] 2722 >>> lst2 = [1, 2, 3] 2723 >>> lst3 = [4, 5, 6] 2724 >>> it(lst1).concat(lst2, lst3).to_list() 2725 ['a', 'b', 'c', 1, 2, 3, 4, 5, 6] 2726 """ 2727 from .concat import ConcatTransform 2728 2729 return it(ConcatTransform([self, *other])) 2730 2731 def intersect(self, *other: Iterable[T]) -> Stream[T]: 2732 """ 2733 Returns a set containing all elements that are contained by both this collection and the specified collection. 2734 2735 The returned set preserves the element iteration order of the original collection. 2736 2737 To get a set containing all elements that are contained at least in one of these collections use union. 2738 2739 Example 1: 2740 >>> lst1 = ['a', 'b', 'c'] 2741 >>> lst2 = ['a2', 'b2', 'c'] 2742 >>> it(lst1).intersect(lst2).to_list() 2743 ['c'] 2744 2745 Example 2: 2746 >>> lst1 = ['a', 'b', 'c'] 2747 >>> lst2 = ['a2', 'b', 'c'] 2748 >>> lst3 = ['a3', 'b', 'c3'] 2749 >>> it(lst1).intersect(lst2, lst3).to_list() 2750 ['b'] 2751 2752 2753 Example 1: 2754 >>> lst1 = ['a', 'a', 'c'] 2755 >>> lst2 = ['a2', 'b2', 'a'] 2756 >>> it(lst1).intersect(lst2).to_list() 2757 ['a'] 2758 """ 2759 from .intersection import IntersectionTransform 2760 2761 return it(IntersectionTransform([self, *other])) 2762 2763 def union(self, *other: Stream[T]) -> Stream[T]: 2764 """ 2765 Returns a set containing all distinct elements from both collections. 2766 2767 The returned set preserves the element iteration order of the original collection. Those elements of the other collection that are unique are iterated in the end in the order of the other collection. 2768 2769 To get a set containing all elements that are contained in both collections use intersect. 2770 2771 Example 1: 2772 >>> lst1 = ['a', 'b', 'c'] 2773 >>> lst2 = ['a2', 'b2', 'c'] 2774 >>> it(lst1).union(lst2).to_list() 2775 ['a', 'b', 'c', 'a2', 'b2'] 2776 2777 Example 2: 2778 >>> lst1 = ['a', 'b', 'c'] 2779 >>> lst2 = ['a2', 'b', 'c'] 2780 >>> lst3 = ['a3', 'b', 'c3'] 2781 >>> it(lst1).union(lst2, lst3).to_list() 2782 ['a', 'b', 'c', 'a2', 'a3', 'c3'] 2783 2784 2785 Example 1: 2786 >>> lst1 = ['a', 'a', 'c'] 2787 >>> lst2 = ['a2', 'b2', 'a'] 2788 >>> it(lst1).union(lst2).to_list() 2789 ['a', 'c', 'a2', 'b2'] 2790 """ 2791 return self.concat(*other).distinct() 2792 2793 def join(self: Stream[str], separator: str = " ") -> str: 2794 """ 2795 Joins the elements of the given Stream into a string. 2796 2797 Example 1: 2798 >>> lst = ['a', 'b', 'c'] 2799 >>> it(lst).join(', ') 2800 'a, b, c' 2801 """ 2802 return separator.join(self) 2803 2804 @overload 2805 def progress(self) -> Stream[T]: ... 2806 @overload 2807 def progress( 2808 self, progress_func: Union[Literal["tqdm"], Literal["tqdm_rich"]] 2809 ) -> Stream[T]: ... 2810 @overload 2811 def progress(self, progress_func: Callable[[Stream[T]], Iterable[T]]) -> Stream[T]: ... 2812 def progress( 2813 self, 2814 progress_func: Union[ 2815 Callable[[Stream[T]], Iterable[T]], 2816 Literal["tqdm"], 2817 Literal["tqdm_rich"], 2818 None, 2819 ] = None, 2820 ) -> Stream[T]: 2821 """ 2822 Returns a Stream that enable a progress bar for the given Stream. 2823 2824 Example 1: 2825 >>> from tqdm import tqdm 2826 >>> from time import sleep 2827 >>> it(range(10)).progress(lambda x: tqdm(x, total=len(x))).parallel_map(lambda x: sleep(0.), max_workers=5).to_list() and None 2828 >>> for _ in it(list(range(10))).progress(lambda x: tqdm(x, total=len(x))).to_list(): pass 2829 """ 2830 if progress_func is not None and callable(progress_func): 2831 return it(progress_func(self)) 2832 2833 def import_tqdm(): 2834 if progress_func == "tqdm_rich": 2835 import warnings 2836 from tqdm.rich import tqdm 2837 from tqdm import TqdmExperimentalWarning 2838 2839 warnings.filterwarnings("ignore", category=TqdmExperimentalWarning) 2840 else: 2841 from tqdm import tqdm 2842 return tqdm 2843 2844 try: 2845 tqdm = import_tqdm() 2846 except ImportError: 2847 from pip import main as pip # type: ignore 2848 2849 pip(["install", "tqdm"]) 2850 tqdm = import_tqdm() 2851 2852 return it(tqdm(self, total=len(self))) 2853 2854 def typing_as(self, typ: Type[U]) -> Stream[U]: 2855 """ 2856 Cast the element as specific Type to gain code completion base on type annotations. 2857 """ 2858 el = self.first_not_none_of_or_none() 2859 if el is None or isinstance(el, typ) or not isinstance(el, dict): 2860 return self # type: ignore 2861 2862 class AttrDict(Dict[str, Any]): 2863 def __init__(self, value: Dict[str, Any]) -> None: 2864 super().__init__(**value) 2865 setattr(self, "__dict__", value) 2866 self.__getattr__ = value.__getitem__ 2867 self.__setattr__ = value.__setattr__ # type: ignore 2868 2869 return self.map(AttrDict) # type: ignore # use https://github.com/cdgriffith/Box ? 2870 2871 def to_set(self) -> Set[T]: 2872 """ 2873 Returns a set containing all elements of this Stream. 2874 2875 Example 1: 2876 >>> it(['a', 'b', 'c', 'c']).to_set() == {'a', 'b', 'c'} 2877 True 2878 """ 2879 return set(self) 2880 2881 @overload 2882 def to_dict(self: Stream[Tuple[K, V]]) -> Dict[K, V]: ... 2883 @overload 2884 def to_dict(self, transform: Callable[[T], Tuple[K, V]]) -> Dict[K, V]: ... 2885 @overload 2886 def to_dict(self, transform: Callable[[T, int], Tuple[K, V]]) -> Dict[K, V]: ... 2887 @overload 2888 def to_dict(self, transform: Callable[[T, int, Stream[T]], Tuple[K, V]]) -> Dict[K, V]: ... 2889 def to_dict(self, transform: Optional[Callable[..., Tuple[K, V]]] = None) -> Dict[K, V]: 2890 """ 2891 Returns a [Dict] containing key-value Tuple provided by [transform] function 2892 applied to elements of the given Stream. 2893 2894 Example 1: 2895 >>> lst = ['1', '2', '3'] 2896 >>> it(lst).to_dict(lambda x: (int(x), x)) 2897 {1: '1', 2: '2', 3: '3'} 2898 2899 Example 2: 2900 >>> lst = [(1, '1'), (2, '2'), (3, '3')] 2901 >>> it(lst).to_dict() 2902 {1: '1', 2: '2', 3: '3'} 2903 """ 2904 return self.associate(transform or (lambda x: x)) # type: ignore 2905 2906 def to_list(self) -> List[T]: 2907 """ 2908 Returns a list with elements of the given Stream. 2909 2910 Example 1: 2911 >>> it(['b', 'c', 'a']).to_list() 2912 ['b', 'c', 'a'] 2913 """ 2914 if self.__transform__.cache is not None: 2915 return self.__transform__.cache.copy() 2916 return [s for s in self] 2917 2918 async def to_list_async(self: Iterable[Awaitable[T]]) -> List[T]: 2919 """ 2920 Returns a list with elements of the given Stream. 2921 2922 Example 1: 2923 >>> it(['b', 'c', 'a']).to_list() 2924 ['b', 'c', 'a'] 2925 """ 2926 from asyncio import gather 2927 2928 return await gather(*self) # type: ignore 2929 2930 def let(self, block: Callable[[Stream[T]], U]) -> U: 2931 """ 2932 Calls the specified function [block] with `self` value as its argument and returns its result. 2933 2934 Example 1: 2935 >>> it(['a', 'b', 'c']).let(lambda x: x.map(lambda y: y + '!')).to_list() 2936 ['a!', 'b!', 'c!'] 2937 """ 2938 return block(self) 2939 2940 def also(self, block: Callable[[Stream[T]], Any]) -> Stream[T]: 2941 """ 2942 Calls the specified function [block] with `self` value as its argument and returns `self` value. 2943 2944 Example 1: 2945 >>> it(['a', 'b', 'c']).also(lambda x: x.map(lambda y: y + '!')).to_list() 2946 ['a', 'b', 'c'] 2947 """ 2948 block(self) 2949 return self 2950 2951 @property 2952 def size(self) -> int: 2953 """ 2954 Returns the size of the given Stream. 2955 """ 2956 return len(self.data) 2957 2958 def is_empty(self) -> bool: 2959 """ 2960 Returns True if the Stream is empty, False otherwise. 2961 2962 Example 1: 2963 >>> it(['a', 'b', 'c']).is_empty() 2964 False 2965 2966 Example 2: 2967 >>> it([None]).is_empty() 2968 False 2969 2970 Example 3: 2971 >>> it([]).is_empty() 2972 True 2973 """ 2974 return id(self.first_or_default(self)) == id(self) 2975 2976 def __iter__(self) -> Iterator[T]: 2977 return self.__do_iter__() 2978 2979 def iter(self) -> Iterator[T]: 2980 return self.__do_iter__() 2981 2982 def __do_iter__(self) -> Iterator[T]: 2983 yield from self.__transform__ 2984 2985 def __len__(self) -> int: 2986 return len(self.__transform__) 2987 2988 def __bool__(self) -> bool: 2989 return not self.is_empty() 2990 2991 def __repr__(self) -> str: 2992 if self.__transform__.cache is None: 2993 return "[...]" 2994 return repr(self.to_list()) 2995 2996 def __getitem__(self, key: int) -> T: 2997 """ 2998 Returns the element at the specified [index] in the Stream. 2999 3000 Example 1: 3001 >>> lst = [1, 2, 3] 3002 >>> it(lst)[1] 3003 2 3004 3005 Example 2: 3006 >>> lst = [1, 2, 3] 3007 >>> it(lst)[3] 3008 Traceback (most recent call last): 3009 ... 3010 IndexError: Index 3 out of range 3011 """ 3012 return self.element_at(key) 3013 3014 @overload 3015 def __callback_overload_warpper__(self, callback: Callable[[T], U]) -> Callable[[T], U]: ... 3016 @overload 3017 def __callback_overload_warpper__( 3018 self, callback: Callable[[T, int], U] 3019 ) -> Callable[[T], U]: ... 3020 @overload 3021 def __callback_overload_warpper__( 3022 self, callback: Callable[[T, int, Stream[T]], U] 3023 ) -> Callable[[T], U]: ... 3024 def __callback_overload_warpper__(self, callback: Callable[..., U]) -> Callable[[T], U]: 3025 if hasattr(callback, "__code__"): 3026 if callback.__code__.co_argcount == 2: 3027 index = AutoIncrementIndex() 3028 return lambda x: callback(x, index()) 3029 if callback.__code__.co_argcount == 3: 3030 index = AutoIncrementIndex() 3031 return lambda x: callback(x, index(), self) 3032 return callback
Given an [iterator] function constructs a [Stream] that returns values through the [Iterator] provided by that function.
The values are evaluated lazily, and the sequence is potentially infinite.
77 def dedup(self) -> Stream[T]: 78 """ 79 Removes consecutive repeated elements in the sequence. 80 81 If the sequence is sorted, this removes all duplicates. 82 83 Example 1: 84 >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1'] 85 >>> it(lst).dedup().to_list() 86 ['a1', 'b2', 'a2', 'a1'] 87 88 Example 1: 89 >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1'] 90 >>> it(lst).sorted().dedup().to_list() 91 ['a1', 'a2', 'b2'] 92 """ 93 return self.dedup_by(lambda x: x)
Removes consecutive repeated elements in the sequence.
If the sequence is sorted, this removes all duplicates.
Example 1:
>>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
>>> it(lst)pyiter.dedup().to_list()
['a1', 'b2', 'a2', 'a1']
Example 1:
>>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
>>> it(lst).sorted()pyiter.dedup().to_list()
['a1', 'a2', 'b2']
101 def dedup_by(self, key_selector: Callable[..., Any]) -> Stream[T]: 102 """ 103 Removes all but the first of consecutive elements in the sequence that resolve to the same key. 104 """ 105 return self.dedup_into_group_by(key_selector).map(lambda x: x[0])
Removes all but the first of consecutive elements in the sequence that resolve to the same key.
117 def dedup_with_count_by(self, key_selector: Callable[..., Any]) -> Stream[Tuple[T, int]]: 118 """ 119 Removes all but the first of consecutive elements and its count that resolve to the same key. 120 121 Example 1: 122 >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1'] 123 >>> it(lst).dedup_with_count_by(lambda x: x).to_list() 124 [('a1', 2), ('b2', 1), ('a2', 1), ('a1', 1)] 125 126 Example 1: 127 >>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1'] 128 >>> it(lst).sorted().dedup_with_count_by(lambda x: x).to_list() 129 [('a1', 3), ('a2', 1), ('b2', 1)] 130 """ 131 return self.dedup_into_group_by(key_selector).map(lambda x: (x[0], len(x)))
Removes all but the first of consecutive elements and its count that resolve to the same key.
Example 1:
>>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
>>> it(lst).dedup_with_count_by(lambda x: x).to_list()
[('a1', 2), ('b2', 1), ('a2', 1), ('a1', 1)]
Example 1:
>>> lst = [ 'a1', 'a1', 'b2', 'a2', 'a1']
>>> it(lst).sorted().dedup_with_count_by(lambda x: x).to_list()
[('a1', 3), ('a2', 1), ('b2', 1)]
152 def filter(self, predicate: Callable[..., bool]) -> Stream[T]: 153 """ 154 Returns a Stream containing only elements matching the given [predicate]. 155 156 Example 1: 157 >>> lst = [ 'a1', 'b1', 'b2', 'a2'] 158 >>> it(lst).filter(lambda x: x.startswith('a')).to_list() 159 ['a1', 'a2'] 160 161 Example 2: 162 >>> lst = [ 'a1', 'b1', 'b2', 'a2'] 163 >>> it(lst).filter(lambda x, i: x.startswith('a') or i % 2 == 0 ).to_list() 164 ['a1', 'b2', 'a2'] 165 """ 166 from .filtering import FilteringTransform 167 168 return it(FilteringTransform(self, self.__callback_overload_warpper__(predicate)))
Returns a Stream containing only elements matching the given [predicate].
Example 1:
>>> lst = [ 'a1', 'b1', 'b2', 'a2']
>>> it(lst).filter(lambda x: x.startswith('a')).to_list()
['a1', 'a2']
Example 2:
>>> lst = [ 'a1', 'b1', 'b2', 'a2']
>>> it(lst).filter(lambda x, i: x.startswith('a') or i % 2 == 0 ).to_list()
['a1', 'b2', 'a2']
170 def filter_is_instance(self, typ: Type[U]) -> Stream[U]: 171 """ 172 Returns a Stream containing all elements that are instances of specified type parameter typ. 173 174 Example 1: 175 >>> lst = [ 'a1', 1, 'b2', 3] 176 >>> it(lst).filter_is_instance(int).to_list() 177 [1, 3] 178 179 """ 180 from .type_guard import TypeGuardTransform, TypeGuard 181 182 def guard(x: T) -> TypeGuard[U]: 183 return isinstance(x, typ) 184 185 return it(TypeGuardTransform(self, guard))
Returns a Stream containing all elements that are instances of specified type parameter typ.
Example 1:
>>> lst = [ 'a1', 1, 'b2', 3]
>>> it(lst).filter_is_instance(int).to_list()
[1, 3]
193 def filter_not(self, predicate: Callable[..., bool]) -> Stream[T]: 194 """ 195 Returns a Stream containing all elements not matching the given [predicate]. 196 197 Example 1: 198 >>> lst = [ 'a1', 'b1', 'b2', 'a2'] 199 >>> it(lst).filter_not(lambda x: x.startswith('a')).to_list() 200 ['b1', 'b2'] 201 202 Example 2: 203 >>> lst = [ 'a1', 'a2', 'b1', 'b2'] 204 >>> it(lst).filter_not(lambda x, i: x.startswith('a') and i % 2 == 0 ).to_list() 205 ['a2', 'b1', 'b2'] 206 """ 207 predicate = self.__callback_overload_warpper__(predicate) 208 return self.filter(lambda x: not predicate(x))
Returns a Stream containing all elements not matching the given [predicate].
Example 1:
>>> lst = [ 'a1', 'b1', 'b2', 'a2']
>>> it(lst).filter_not(lambda x: x.startswith('a')).to_list()
['b1', 'b2']
Example 2:
>>> lst = [ 'a1', 'a2', 'b1', 'b2']
>>> it(lst).filter_not(lambda x, i: x.startswith('a') and i % 2 == 0 ).to_list()
['a2', 'b1', 'b2']
214 def filter_not_none(self: Stream[Optional[U]]) -> Stream[U]: 215 """ 216 Returns a Stream containing all elements that are not `None`. 217 218 Example 1: 219 >>> lst = [ 'a', None, 'b'] 220 >>> it(lst).filter_not_none().to_list() 221 ['a', 'b'] 222 """ 223 from .type_guard import TypeGuardTransform, TypeGuard 224 225 def guard(x: Optional[U]) -> TypeGuard[U]: 226 return x is not None 227 228 return it(TypeGuardTransform(self, guard))
Returns a Stream containing all elements that are not None.
Example 1:
>>> lst = [ 'a', None, 'b']
>>> it(lst).filter_not_none().to_list()
['a', 'b']
258 def map( 259 self, transform: Callable[..., U], return_exceptions: bool = False 260 ) -> Union[Stream[U], Stream[Union[U, BaseException]]]: 261 """ 262 Returns a Stream containing the results of applying the given [transform] function 263 to each element in the original Stream. 264 265 Example 1: 266 >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}] 267 >>> it(lst).map(lambda x: x['age']).to_list() 268 [12, 13] 269 270 Example 2: 271 >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}] 272 >>> it(lst).map(lambda x, i: x['name'] + str(i)).to_list() 273 ['A0', 'B1'] 274 275 Example 3: 276 >>> lst = ['hi', 'abc'] 277 >>> it(lst).map(len).to_list() 278 [2, 3] 279 """ 280 from .mapping import MappingTransform 281 282 transform = self.__callback_overload_warpper__(transform) 283 if return_exceptions: 284 285 def transform_wrapper(x: T) -> Union[U, BaseException]: 286 try: 287 return transform(x) 288 except BaseException as e: 289 return e 290 291 return it(MappingTransform(self, transform_wrapper)) 292 293 return it(MappingTransform(self, transform))
Returns a Stream containing the results of applying the given [transform] function to each element in the original Stream.
Example 1:
>>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
>>> it(lst).map(lambda x: x['age']).to_list()
[12, 13]
Example 2:
>>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
>>> it(lst).map(lambda x, i: x['name'] + str(i)).to_list()
['A0', 'B1']
Example 3:
>>> lst = ['hi', 'abc']
>>> it(lst).map(len).to_list()
[2, 3]
309 async def map_async( 310 self, transform: Callable[..., Awaitable[U]], return_exceptions: bool = False 311 ) -> Union[Stream[U], Stream[Union[U, BaseException]]]: 312 """ 313 Similar to `.map()` but you can input a async transform then await it. 314 """ 315 from asyncio import gather 316 317 if return_exceptions: 318 return it(await gather(*self.map(transform), return_exceptions=True)) 319 return it(await gather(*self.map(transform)))
Similar to .map() but you can input a async transform then await it.
327 def map_not_none(self, transform: Callable[..., Optional[U]]) -> Stream[U]: 328 """ 329 Returns a Stream containing only the non-none results of applying the given [transform] function 330 to each element in the original collection. 331 332 Example 1: 333 >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': None}] 334 >>> it(lst).map_not_none(lambda x: x['age']).to_list() 335 [12] 336 """ 337 return self.map(transform).filter_not_none() # type: ignore
Returns a Stream containing only the non-none results of applying the given [transform] function to each element in the original collection.
Example 1:
>>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': None}]
>>> it(lst).map_not_none(lambda x: x['age']).to_list()
[12]
363 def parallel_map( 364 self, 365 transform: Callable[..., U], 366 max_workers: Optional[int] = None, 367 chunksize: int = 1, 368 executor: ParallelMappingTransform.Executor = "Thread", 369 ) -> Stream[U]: 370 """ 371 Returns a Stream containing the results of applying the given [transform] function 372 to each element in the original Stream. 373 374 Example 1: 375 >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}] 376 >>> it(lst).parallel_map(lambda x: x['age']).to_list() 377 [12, 13] 378 379 Example 2: 380 >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}] 381 >>> it(lst).parallel_map(lambda x: x['age'], max_workers=2).to_list() 382 [12, 13] 383 384 Example 3: 385 >>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}] 386 >>> it(lst).parallel_map(lambda x, i: x['age'] + i, max_workers=2).to_list() 387 [12, 14] 388 """ 389 from .parallel_mapping import ParallelMappingTransform 390 391 return it( 392 ParallelMappingTransform( 393 self, 394 self.__callback_overload_warpper__(transform), 395 max_workers, 396 chunksize, 397 executor, 398 ) 399 )
Returns a Stream containing the results of applying the given [transform] function to each element in the original Stream.
Example 1:
>>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
>>> it(lst).parallel_map(lambda x: x['age']).to_list()
[12, 13]
Example 2:
>>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
>>> it(lst).parallel_map(lambda x: x['age'], max_workers=2).to_list()
[12, 13]
Example 3:
>>> lst = [{ 'name': 'A', 'age': 12}, { 'name': 'B', 'age': 13}]
>>> it(lst).parallel_map(lambda x, i: x['age'] + i, max_workers=2).to_list()
[12, 14]
407 def find(self, predicate: Callable[..., bool]) -> Optional[T]: 408 """ 409 Returns the first element matching the given [predicate], or `None` if no such element was found. 410 411 Example 1: 412 >>> lst = ['a', 'b', 'c'] 413 >>> it(lst).find(lambda x: x == 'b') 414 'b' 415 """ 416 return self.first_or_none(predicate)
Returns the first element matching the given [predicate], or None if no such element was found.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).find(lambda x: x == 'b')
'b'
418 def find_last(self, predicate: Callable[[T], bool]) -> Optional[T]: 419 """ 420 Returns the last element matching the given [predicate], or `None` if no such element was found. 421 422 Example 1: 423 >>> lst = ['a', 'b', 'c'] 424 >>> it(lst).find_last(lambda x: x == 'b') 425 'b' 426 """ 427 return self.last_or_none(predicate)
Returns the last element matching the given [predicate], or None if no such element was found.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).find_last(lambda x: x == 'b')
'b'
437 def first(self, predicate: Optional[Callable[..., bool]] = None) -> T: 438 """ 439 Returns first element. 440 441 Example 1: 442 >>> lst = ['a', 'b', 'c'] 443 >>> it(lst).first() 444 'a' 445 446 Example 2: 447 >>> lst = [] 448 >>> it(lst).first() 449 Traceback (most recent call last): 450 ... 451 ValueError: Stream is empty. 452 453 Example 3: 454 >>> lst = ['a', 'b', 'c'] 455 >>> it(lst).first(lambda x: x == 'b') 456 'b' 457 458 Example 4: 459 >>> lst = ['a', 'b', 'c'] 460 >>> it(lst).first(lambda x: x == 'd') 461 Traceback (most recent call last): 462 ... 463 ValueError: Stream is empty. 464 465 Example 5: 466 >>> lst = [None] 467 >>> it(lst).first() is None 468 True 469 """ 470 for e in self: 471 if predicate is None or predicate(e): 472 return e 473 raise ValueError("Stream is empty.")
Returns first element.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).first()
'a'
Example 2:
>>> lst = []
>>> it(lst).first()
Traceback (most recent call last):
...
ValueError: Stream is empty.
Example 3:
>>> lst = ['a', 'b', 'c']
>>> it(lst).first(lambda x: x == 'b')
'b'
Example 4:
>>> lst = ['a', 'b', 'c']
>>> it(lst).first(lambda x: x == 'd')
Traceback (most recent call last):
...
ValueError: Stream is empty.
Example 5:
>>> lst = [None]
>>> it(lst).first() is None
True
491 def first_not_none_of( 492 self: Stream[Optional[U]], 493 transform: Optional[Callable[..., Optional[U]]] = None, 494 ) -> U: 495 """ 496 Returns the first non-`None` result of applying the given [transform] function to each element in the original collection. 497 498 Example 1: 499 >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': 12}] 500 >>> it(lst).first_not_none_of(lambda x: x['age']) 501 12 502 503 Example 2: 504 >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': None}] 505 >>> it(lst).first_not_none_of(lambda x: x['age']) 506 Traceback (most recent call last): 507 ... 508 ValueError: No element of the Stream was transformed to a non-none value. 509 """ 510 511 v = ( 512 self.first_not_none_of_or_none() 513 if transform is None 514 else self.first_not_none_of_or_none(transform) 515 ) 516 if v is None: 517 raise ValueError("No element of the Stream was transformed to a non-none value.") 518 return v
Returns the first non-None result of applying the given [transform] function to each element in the original collection.
Example 1:
>>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': 12}]
>>> it(lst).first_not_none_of(lambda x: x['age'])
12
Example 2:
>>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': None}]
>>> it(lst).first_not_none_of(lambda x: x['age'])
Traceback (most recent call last):
...
ValueError: No element of the Stream was transformed to a non-none value.
530 def first_not_none_of_or_none( 531 self, transform: Optional[Callable[..., T]] = None 532 ) -> Optional[T]: 533 """ 534 Returns the first non-`None` result of applying the given [transform] function to each element in the original collection. 535 536 Example 1: 537 >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': 12}] 538 >>> it(lst).first_not_none_of_or_none(lambda x: x['age']) 539 12 540 541 Example 2: 542 >>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': None}] 543 >>> it(lst).first_not_none_of_or_none(lambda x: x['age']) is None 544 True 545 """ 546 if transform is None: 547 return self.first_or_none() 548 return self.map_not_none(transform).first_or_none()
Returns the first non-None result of applying the given [transform] function to each element in the original collection.
Example 1:
>>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': 12}]
>>> it(lst).first_not_none_of_or_none(lambda x: x['age'])
12
Example 2:
>>> lst = [{ 'name': 'A', 'age': None}, { 'name': 'B', 'age': None}]
>>> it(lst).first_not_none_of_or_none(lambda x: x['age']) is None
True
558 def first_or_none(self, predicate: Optional[Callable[..., bool]] = None) -> Optional[T]: 559 """ 560 Returns the first element, or `None` if the Stream is empty. 561 562 Example 1: 563 >>> lst = [] 564 >>> it(lst).first_or_none() is None 565 True 566 567 Example 2: 568 >>> lst = ['a', 'b', 'c'] 569 >>> it(lst).first_or_none() 570 'a' 571 572 Example 2: 573 >>> lst = ['a', 'b', 'c'] 574 >>> it(lst).first_or_none(lambda x: x == 'b') 575 'b' 576 """ 577 if predicate is not None: 578 return self.first_or_default(predicate, None) 579 else: 580 return self.first_or_default(None)
Returns the first element, or None if the Stream is empty.
Example 1:
>>> lst = []
>>> it(lst).first_or_none() is None
True
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).first_or_none()
'a'
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).first_or_none(lambda x: x == 'b')
'b'
592 def first_or_default( # type: ignore 593 self, predicate: Union[Callable[..., bool], U], default: Optional[U] = None 594 ) -> Union[T, U, None]: 595 """ 596 Returns the first element, or the given [default] if the Stream is empty. 597 598 Example 1: 599 >>> lst = [] 600 >>> it(lst).first_or_default('a') 601 'a' 602 603 Example 2: 604 >>> lst = ['b'] 605 >>> it(lst).first_or_default('a') 606 'b' 607 608 Example 3: 609 >>> lst = ['a', 'b', 'c'] 610 >>> it(lst).first_or_default(lambda x: x == 'b', 'd') 611 'b' 612 613 Example 4: 614 >>> lst = [] 615 >>> it(lst).first_or_default(lambda x: x == 'b', 'd') 616 'd' 617 """ 618 seq = self 619 if isinstance(predicate, Callable): 620 seq = self.filter(predicate) # type: ignore 621 else: 622 default = predicate 623 return next(iter(seq), default)
Returns the first element, or the given [default] if the Stream is empty.
Example 1:
>>> lst = []
>>> it(lst).first_or_default('a')
'a'
Example 2:
>>> lst = ['b']
>>> it(lst).first_or_default('a')
'b'
Example 3:
>>> lst = ['a', 'b', 'c']
>>> it(lst).first_or_default(lambda x: x == 'b', 'd')
'b'
Example 4:
>>> lst = []
>>> it(lst).first_or_default(lambda x: x == 'b', 'd')
'd'
633 def last(self, predicate: Optional[Callable[..., bool]] = None) -> T: 634 """ 635 Returns last element. 636 637 Example 1: 638 >>> lst = ['a', 'b', 'c'] 639 >>> it(lst).last() 640 'c' 641 642 Example 2: 643 >>> lst = [] 644 >>> it(lst).last() 645 Traceback (most recent call last): 646 ... 647 ValueError: Stream is empty. 648 """ 649 v = self.last_or_none(predicate) if predicate is not None else self.last_or_none() 650 if v is None: 651 raise ValueError("Stream is empty.") 652 return v
Returns last element.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).last()
'c'
Example 2:
>>> lst = []
>>> it(lst).last()
Traceback (most recent call last):
...
ValueError: Stream is empty.
662 def last_or_none(self, predicate: Optional[Callable[..., bool]] = None) -> Optional[T]: 663 """ 664 Returns the last element matching the given [predicate], or `None` if no such element was found. 665 666 Exmaple 1: 667 >>> lst = ['a', 'b', 'c'] 668 >>> it(lst).last_or_none() 669 'c' 670 671 Exmaple 2: 672 >>> lst = ['a', 'b', 'c'] 673 >>> it(lst).last_or_none(lambda x: x != 'c') 674 'b' 675 676 Exmaple 3: 677 >>> lst = [] 678 >>> it(lst).last_or_none(lambda x: x != 'c') is None 679 True 680 """ 681 last: Optional[T] = None 682 for i in self if predicate is None else self.filter(predicate): 683 last = i 684 return last
Returns the last element matching the given [predicate], or None if no such element was found.
Exmaple 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).last_or_none()
'c'
Exmaple 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).last_or_none(lambda x: x != 'c')
'b'
Exmaple 3:
>>> lst = []
>>> it(lst).last_or_none(lambda x: x != 'c') is None
True
686 def index_of_or_none(self, element: T) -> Optional[int]: 687 """ 688 Returns first index of [element], or None if the collection does not contain element. 689 690 Example 1: 691 >>> lst = ['a', 'b', 'c'] 692 >>> it(lst).index_of_or_none('b') 693 1 694 695 Example 2: 696 >>> lst = ['a', 'b', 'c'] 697 >>> it(lst).index_of_or_none('d') 698 """ 699 for i, x in enumerate(self): 700 if x == element: 701 return i 702 return None
Returns first index of [element], or None if the collection does not contain element.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_or_none('b')
1
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_or_none('d')
704 def index_of(self, element: T) -> int: 705 """ 706 Returns first index of [element], or -1 if the collection does not contain element. 707 708 Example 1: 709 >>> lst = ['a', 'b', 'c'] 710 >>> it(lst).index_of('b') 711 1 712 713 Example 2: 714 >>> lst = ['a', 'b', 'c'] 715 >>> it(lst).index_of('d') 716 -1 717 """ 718 return none_or(self.index_of_or_none(element), -1)
Returns first index of [element], or -1 if the collection does not contain element.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of('b')
1
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of('d')
-1
720 def index_of_or(self, element: T, default: int) -> int: 721 """ 722 Returns first index of [element], or default value if the collection does not contain element. 723 724 Example 1: 725 >>> lst = ['a', 'b', 'c'] 726 >>> it(lst).index_of_or('b', 1) 727 1 728 729 Example 2: 730 >>> lst = ['a', 'b', 'c'] 731 >>> it(lst).index_of_or('d', 0) 732 0 733 """ 734 return none_or(self.index_of_or_none(element), default)
Returns first index of [element], or default value if the collection does not contain element.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_or('b', 1)
1
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_or('d', 0)
0
736 def index_of_or_else(self, element: T, f: Callable[[], int]) -> int: 737 """ 738 Returns first index of [element], or computes the value from a callback if the collection does not contain element. 739 740 Example 1: 741 >>> lst = ['a', 'b', 'c'] 742 >>> it(lst).index_of_or_else('b', lambda: 2) 743 1 744 745 Example 2: 746 >>> lst = ['a', 'b', 'c'] 747 >>> it(lst).index_of_or_else('d', lambda: 0) 748 0 749 """ 750 return none_or_else(self.index_of_or_none(element), f)
Returns first index of [element], or computes the value from a callback if the collection does not contain element.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_or_else('b', lambda: 2)
1
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_or_else('d', lambda: 0)
0
752 def last_index_of_or_none(self, element: T) -> Optional[int]: 753 """ 754 Returns last index of [element], or None if the collection does not contain element. 755 756 Example 1: 757 >>> lst = ['a', 'b', 'c', 'b'] 758 >>> it(lst).last_index_of_or_none('b') 759 3 760 761 Example 2: 762 >>> lst = ['a', 'b', 'c'] 763 >>> it(lst).last_index_of_or_none('d') 764 """ 765 seq = self.reversed() 766 last_idx = len(seq) - 1 767 for i, x in enumerate(seq): 768 if x == element: 769 return last_idx - i 770 return None
Returns last index of [element], or None if the collection does not contain element.
Example 1:
>>> lst = ['a', 'b', 'c', 'b']
>>> it(lst).last_index_of_or_none('b')
3
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).last_index_of_or_none('d')
772 def last_index_of(self, element: T) -> int: 773 """ 774 Returns last index of [element], or -1 if the collection does not contain element. 775 776 Example 1: 777 >>> lst = ['a', 'b', 'c', 'b'] 778 >>> it(lst).last_index_of('b') 779 3 780 781 Example 2: 782 >>> lst = ['a', 'b', 'c'] 783 >>> it(lst).last_index_of('d') 784 -1 785 """ 786 return none_or(self.last_index_of_or_none(element), -1)
Returns last index of [element], or -1 if the collection does not contain element.
Example 1:
>>> lst = ['a', 'b', 'c', 'b']
>>> it(lst).last_index_of('b')
3
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).last_index_of('d')
-1
788 def last_index_of_or(self, element: T, default: int) -> int: 789 """ 790 Returns last index of [element], or default value if the collection does not contain element. 791 792 Example 1: 793 >>> lst = ['a', 'b', 'c', 'b'] 794 >>> it(lst).last_index_of_or('b', 0) 795 3 796 797 Example 2: 798 >>> lst = ['a', 'b', 'c'] 799 >>> it(lst).last_index_of_or('d', len(lst)) 800 3 801 """ 802 return none_or(self.last_index_of_or_none(element), default)
Returns last index of [element], or default value if the collection does not contain element.
Example 1:
>>> lst = ['a', 'b', 'c', 'b']
>>> it(lst).last_index_of_or('b', 0)
3
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).last_index_of_or('d', len(lst))
3
804 def last_index_of_or_else(self, element: T, f: Callable[[], int]) -> int: 805 """ 806 Returns last index of [element], or computes the value from a callback if the collection does not contain element. 807 808 Example 1: 809 >>> lst = ['a', 'b', 'c', 'b'] 810 >>> it(lst).last_index_of_or_else('b', lambda: 0) 811 3 812 813 Example 2: 814 >>> lst = ['a', 'b', 'c'] 815 >>> it(lst).last_index_of_or_else('d', lambda: len(lst)) 816 3 817 """ 818 return none_or_else(self.last_index_of_or_none(element), f)
Returns last index of [element], or computes the value from a callback if the collection does not contain element.
Example 1:
>>> lst = ['a', 'b', 'c', 'b']
>>> it(lst).last_index_of_or_else('b', lambda: 0)
3
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).last_index_of_or_else('d', lambda: len(lst))
3
828 def index_of_first_or_none(self, predicate: Callable[..., bool]) -> Optional[int]: 829 """ 830 Returns first index of element matching the given [predicate], or None if no such element was found. 831 832 Example 1: 833 >>> lst = ['a', 'b', 'c'] 834 >>> it(lst).index_of_first_or_none(lambda x: x == 'b') 835 1 836 837 Example 2: 838 >>> lst = ['a', 'b', 'c'] 839 >>> it(lst).index_of_first_or_none(lambda x: x == 'd') 840 """ 841 predicate = self.__callback_overload_warpper__(predicate) 842 for i, x in enumerate(self): 843 if predicate(x): 844 return i 845 return None
Returns first index of element matching the given [predicate], or None if no such element was found.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first_or_none(lambda x: x == 'b')
1
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first_or_none(lambda x: x == 'd')
853 def index_of_first(self, predicate: Callable[..., bool]) -> int: 854 """ 855 Returns first index of element matching the given [predicate], or -1 if no such element was found. 856 857 Example 1: 858 >>> lst = ['a', 'b', 'c'] 859 >>> it(lst).index_of_first(lambda x: x == 'b') 860 1 861 862 Example 2: 863 >>> lst = ['a', 'b', 'c'] 864 >>> it(lst).index_of_first(lambda x: x == 'd') 865 -1 866 867 Example 3: 868 >>> lst = ['a', 'b', 'c'] 869 >>> it(lst).index_of_first(lambda x: x == 'a') 870 0 871 """ 872 return none_or(self.index_of_first_or_none(predicate), -1)
Returns first index of element matching the given [predicate], or -1 if no such element was found.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first(lambda x: x == 'b')
1
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first(lambda x: x == 'd')
-1
Example 3:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first(lambda x: x == 'a')
0
882 def index_of_first_or(self, predicate: Callable[..., bool], default: int) -> int: 883 """ 884 Returns first index of element matching the given [predicate], or default value if no such element was found. 885 886 Example 1: 887 >>> lst = ['a', 'b', 'c'] 888 >>> it(lst).index_of_first_or(lambda x: x == 'b', 0) 889 1 890 891 Example 2: 892 >>> lst = ['a', 'b', 'c'] 893 >>> it(lst).index_of_first_or(lambda x: x == 'd', 0) 894 0 895 896 Example 3: 897 >>> lst = ['a', 'b', 'c'] 898 >>> it(lst).index_of_first_or(lambda x: x == 'a', 0) 899 0 900 """ 901 return none_or(self.index_of_first_or_none(predicate), default)
Returns first index of element matching the given [predicate], or default value if no such element was found.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first_or(lambda x: x == 'b', 0)
1
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first_or(lambda x: x == 'd', 0)
0
Example 3:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first_or(lambda x: x == 'a', 0)
0
915 def index_of_first_or_else(self, predicate: Callable[..., bool], f: Callable[[], int]) -> int: 916 """ 917 Returns first index of element matching the given [predicate], or computes the value from a callback if no such element was found. 918 919 Example 1: 920 >>> lst = ['a', 'b', 'c'] 921 >>> it(lst).index_of_first_or_else(lambda x: x == 'b', lambda: len(lst)) 922 1 923 924 Example 2: 925 >>> lst = ['a', 'b', 'c'] 926 >>> it(lst).index_of_first_or_else(lambda x: x == 'd', lambda: len(lst)) 927 3 928 929 Example 3: 930 >>> lst = ['a', 'b', 'c'] 931 >>> it(lst).index_of_first_or_else(lambda x: x == 'a', lambda: len(lst)) 932 0 933 """ 934 return none_or_else(self.index_of_first_or_none(predicate), f)
Returns first index of element matching the given [predicate], or computes the value from a callback if no such element was found.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first_or_else(lambda x: x == 'b', lambda: len(lst))
1
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first_or_else(lambda x: x == 'd', lambda: len(lst))
3
Example 3:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_first_or_else(lambda x: x == 'a', lambda: len(lst))
0
944 def index_of_last_or_none(self, predicate: Callable[..., bool]) -> Optional[int]: 945 """ 946 Returns last index of element matching the given [predicate], or -1 if no such element was found. 947 948 Example 1: 949 >>> lst = ['a', 'b', 'c', 'b'] 950 >>> it(lst).index_of_last_or_none(lambda x: x == 'b') 951 3 952 953 Example 2: 954 >>> lst = ['a', 'b', 'c'] 955 >>> it(lst).index_of_last_or_none(lambda x: x == 'd') 956 """ 957 seq = self.reversed() 958 last_idx = len(seq) - 1 959 predicate = self.__callback_overload_warpper__(predicate) 960 for i, x in enumerate(seq): 961 if predicate(x): 962 return last_idx - i 963 return None
Returns last index of element matching the given [predicate], or -1 if no such element was found.
Example 1:
>>> lst = ['a', 'b', 'c', 'b']
>>> it(lst).index_of_last_or_none(lambda x: x == 'b')
3
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_last_or_none(lambda x: x == 'd')
971 def index_of_last(self, predicate: Callable[..., bool]) -> int: 972 """ 973 Returns last index of element matching the given [predicate], or -1 if no such element was found. 974 975 Example 1: 976 >>> lst = ['a', 'b', 'c', 'b'] 977 >>> it(lst).index_of_last(lambda x: x == 'b') 978 3 979 980 Example 2: 981 >>> lst = ['a', 'b', 'c'] 982 >>> it(lst).index_of_last(lambda x: x == 'd') 983 -1 984 985 Example 3: 986 >>> lst = ['a', 'b', 'c'] 987 >>> it(lst).index_of_last(lambda x: x == 'a') 988 0 989 """ 990 return none_or(self.index_of_last_or_none(predicate), -1)
Returns last index of element matching the given [predicate], or -1 if no such element was found.
Example 1:
>>> lst = ['a', 'b', 'c', 'b']
>>> it(lst).index_of_last(lambda x: x == 'b')
3
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_last(lambda x: x == 'd')
-1
Example 3:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_last(lambda x: x == 'a')
0
1000 def index_of_last_or(self, predicate: Callable[..., bool], default: int) -> int: 1001 """ 1002 Returns last index of element matching the given [predicate], or default value if no such element was found. 1003 1004 Example 1: 1005 >>> lst = ['a', 'b', 'c', 'b'] 1006 >>> it(lst).index_of_last_or(lambda x: x == 'b', 0) 1007 3 1008 1009 Example 2: 1010 >>> lst = ['a', 'b', 'c'] 1011 >>> it(lst).index_of_last_or(lambda x: x == 'd', -99) 1012 -99 1013 1014 Example 3: 1015 >>> lst = ['a', 'b', 'c'] 1016 >>> it(lst).index_of_last_or(lambda x: x == 'a', 0) 1017 0 1018 """ 1019 return none_or(self.index_of_last_or_none(predicate), default)
Returns last index of element matching the given [predicate], or default value if no such element was found.
Example 1:
>>> lst = ['a', 'b', 'c', 'b']
>>> it(lst).index_of_last_or(lambda x: x == 'b', 0)
3
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_last_or(lambda x: x == 'd', -99)
-99
Example 3:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_last_or(lambda x: x == 'a', 0)
0
1033 def index_of_last_or_else(self, predicate: Callable[..., bool], f: Callable[[], int]) -> int: 1034 """ 1035 Returns last index of element matching the given [predicate], or default value if no such element was found. 1036 1037 Example 1: 1038 >>> lst = ['a', 'b', 'c', 'b'] 1039 >>> it(lst).index_of_last_or_else(lambda x: x == 'b', lambda: -len(lst)) 1040 3 1041 1042 Example 2: 1043 >>> lst = ['a', 'b', 'c'] 1044 >>> it(lst).index_of_last_or_else(lambda x: x == 'd', lambda: -len(lst)) 1045 -3 1046 1047 Example 3: 1048 >>> lst = ['a', 'b', 'c'] 1049 >>> it(lst).index_of_last_or_else(lambda x: x == 'a', lambda: -len(lst)) 1050 0 1051 """ 1052 return none_or_else(self.index_of_last_or_none(predicate), f)
Returns last index of element matching the given [predicate], or default value if no such element was found.
Example 1:
>>> lst = ['a', 'b', 'c', 'b']
>>> it(lst).index_of_last_or_else(lambda x: x == 'b', lambda: -len(lst))
3
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_last_or_else(lambda x: x == 'd', lambda: -len(lst))
-3
Example 3:
>>> lst = ['a', 'b', 'c']
>>> it(lst).index_of_last_or_else(lambda x: x == 'a', lambda: -len(lst))
0
1062 def single(self, predicate: Optional[Callable[..., bool]] = None) -> T: 1063 """ 1064 Returns the single element matching the given [predicate], or throws exception if there is no 1065 or more than one matching element. 1066 1067 Exmaple 1: 1068 >>> lst = ['a'] 1069 >>> it(lst).single() 1070 'a' 1071 1072 Exmaple 2: 1073 >>> lst = [] 1074 >>> it(lst).single() is None 1075 Traceback (most recent call last): 1076 ... 1077 ValueError: Stream contains no element matching the predicate. 1078 1079 Exmaple 2: 1080 >>> lst = ['a', 'b'] 1081 >>> it(lst).single() is None 1082 Traceback (most recent call last): 1083 ... 1084 ValueError: Stream contains more than one matching element. 1085 """ 1086 single: Optional[T] = None 1087 found = False 1088 for i in self if predicate is None else self.filter(predicate): 1089 if found: 1090 raise ValueError("Stream contains more than one matching element.") 1091 single = i 1092 found = True 1093 if single is None: 1094 raise ValueError("Stream contains no element matching the predicate.") 1095 return single
Returns the single element matching the given [predicate], or throws exception if there is no or more than one matching element.
Exmaple 1:
>>> lst = ['a']
>>> it(lst).single()
'a'
Exmaple 2:
>>> lst = []
>>> it(lst).single() is None
Traceback (most recent call last):
...
ValueError: Stream contains no element matching the predicate.
Exmaple 2:
>>> lst = ['a', 'b']
>>> it(lst).single() is None
Traceback (most recent call last):
...
ValueError: Stream contains more than one matching element.
1105 def single_or_none(self, predicate: Optional[Callable[..., bool]] = None) -> Optional[T]: 1106 """ 1107 Returns the single element matching the given [predicate], or `None` if element was not found 1108 or more than one element was found. 1109 1110 Exmaple 1: 1111 >>> lst = ['a'] 1112 >>> it(lst).single_or_none() 1113 'a' 1114 1115 Exmaple 2: 1116 >>> lst = [] 1117 >>> it(lst).single_or_none() 1118 1119 Exmaple 2: 1120 >>> lst = ['a', 'b'] 1121 >>> it(lst).single_or_none() 1122 1123 """ 1124 single: Optional[T] = None 1125 found = False 1126 for i in self if predicate is None else self.filter(predicate): 1127 if found: 1128 return None 1129 single = i 1130 found = True 1131 if not found: 1132 return None 1133 return single
Returns the single element matching the given [predicate], or None if element was not found
or more than one element was found.
Exmaple 1:
>>> lst = ['a']
>>> it(lst).single_or_none()
'a'
Exmaple 2:
>>> lst = []
>>> it(lst).single_or_none()
Exmaple 2:
>>> lst = ['a', 'b']
>>> it(lst).single_or_none()
1136 def drop(self, n: int) -> Stream[T]: 1137 """ 1138 Returns a Stream containing all elements except first [n] elements. 1139 1140 Example 1: 1141 >>> lst = ['a', 'b', 'c'] 1142 >>> it(lst).drop(0).to_list() 1143 ['a', 'b', 'c'] 1144 1145 Example 2: 1146 >>> lst = ['a', 'b', 'c'] 1147 >>> it(lst).drop(1).to_list() 1148 ['b', 'c'] 1149 1150 Example 2: 1151 >>> lst = ['a', 'b', 'c'] 1152 >>> it(lst).drop(4).to_list() 1153 [] 1154 """ 1155 if n < 0: 1156 raise ValueError(f"Requested element count {n} is less than zero.") 1157 if n == 0: 1158 return self 1159 1160 from .drop import DropTransform 1161 1162 return it(DropTransform(self, n))
Returns a Stream containing all elements except first [n] elements.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst)pyiter.drop(0).to_list()
['a', 'b', 'c']
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst)pyiter.drop(1).to_list()
['b', 'c']
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst)pyiter.drop(4).to_list()
[]
1171 def drop_while(self, predicate: Callable[..., bool]) -> Stream[T]: 1172 """ 1173 Returns a Stream containing all elements except first elements that satisfy the given [predicate]. 1174 1175 Example 1: 1176 >>> lst = [1, 2, 3, 4, 1] 1177 >>> it(lst).drop_while(lambda x: x < 3 ).to_list() 1178 [3, 4, 1] 1179 """ 1180 from .drop_while import DropWhileTransform 1181 1182 return it(DropWhileTransform(self, self.__callback_overload_warpper__(predicate)))
Returns a Stream containing all elements except first elements that satisfy the given [predicate].
Example 1:
>>> lst = [1, 2, 3, 4, 1]
>>> it(lst)pyiter.drop_while(lambda x: x < 3 ).to_list()
[3, 4, 1]
1191 def drop_until(self, predicate: Callable[..., bool]) -> Stream[T]: 1192 """ 1193 Returns a Stream containing all elements except the first elements dropped until the first element that satisfies the given [predicate]. 1194 1195 Example 1: 1196 >>> lst = [1, 2, 3, 4, 1] 1197 >>> it(lst).drop_until(lambda x: x >= 3).to_list() 1198 [3, 4, 1] 1199 1200 Example 2: 1201 >>> lst = [1, 2, 1, 4] 1202 >>> it(lst).drop_until(lambda x: x == 4).to_list() 1203 [4] 1204 """ 1205 from .drop_until import DropUntilTransform 1206 1207 return it(DropUntilTransform(self, self.__callback_overload_warpper__(predicate)))
Returns a Stream containing all elements except the first elements dropped until the first element that satisfies the given [predicate].
Example 1:
>>> lst = [1, 2, 3, 4, 1]
>>> it(lst)pyiter.drop_until(lambda x: x >= 3).to_list()
[3, 4, 1]
Example 2:
>>> lst = [1, 2, 1, 4]
>>> it(lst)pyiter.drop_until(lambda x: x == 4).to_list()
[4]
1209 def drop_last(self, n: int) -> Stream[T]: 1210 """ 1211 Returns a Stream containing all elements except last [n] elements. 1212 1213 Example 1: 1214 >>> lst = ['a', 'b', 'c'] 1215 >>> it(lst).drop_last(0).to_list() 1216 ['a', 'b', 'c'] 1217 1218 Example 2: 1219 >>> lst = ['a', 'b', 'c'] 1220 >>> it(lst).drop_last(1).to_list() 1221 ['a', 'b'] 1222 1223 Example 3: 1224 >>> lst = ['a', 'b', 'c'] 1225 >>> it(lst).drop_last(4).to_list() 1226 [] 1227 """ 1228 if n < 0: 1229 raise ValueError(f"Requested element count {n} is less than zero.") 1230 if n == 0: 1231 return self 1232 1233 size = len(self) 1234 if size <= n: 1235 return Stream([]) 1236 return self.take(size - n)
Returns a Stream containing all elements except last [n] elements.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).drop_last(0).to_list()
['a', 'b', 'c']
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).drop_last(1).to_list()
['a', 'b']
Example 3:
>>> lst = ['a', 'b', 'c']
>>> it(lst).drop_last(4).to_list()
[]
1238 def skip(self, n: int) -> Stream[T]: 1239 """ 1240 Returns a Stream containing all elements except first [n] elements. 1241 1242 Example 1: 1243 >>> lst = ['a', 'b', 'c'] 1244 >>> it(lst).skip(0).to_list() 1245 ['a', 'b', 'c'] 1246 1247 Example 2: 1248 >>> lst = ['a', 'b', 'c'] 1249 >>> it(lst).skip(1).to_list() 1250 ['b', 'c'] 1251 1252 Example 2: 1253 >>> lst = ['a', 'b', 'c'] 1254 >>> it(lst).skip(4).to_list() 1255 [] 1256 """ 1257 return self.drop(n)
Returns a Stream containing all elements except first [n] elements.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).skip(0).to_list()
['a', 'b', 'c']
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).skip(1).to_list()
['b', 'c']
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).skip(4).to_list()
[]
1265 def skip_while(self, predicate: Callable[..., bool]) -> Stream[T]: 1266 """ 1267 Returns a Stream containing all elements except first elements that satisfy the given [predicate]. 1268 1269 Example 1: 1270 >>> lst = [1, 2, 3, 4, 1] 1271 >>> it(lst).skip_while(lambda x: x < 3 ).to_list() 1272 [3, 4, 1] 1273 """ 1274 return self.drop_while(predicate)
Returns a Stream containing all elements except first elements that satisfy the given [predicate].
Example 1:
>>> lst = [1, 2, 3, 4, 1]
>>> it(lst).skip_while(lambda x: x < 3 ).to_list()
[3, 4, 1]
1276 def take(self, n: int) -> Stream[T]: 1277 """ 1278 Returns an Stream containing first [n] elements. 1279 1280 Example 1: 1281 >>> a = ['a', 'b', 'c'] 1282 >>> it(a).take(0).to_list() 1283 [] 1284 1285 Example 2: 1286 >>> a = ['a', 'b', 'c'] 1287 >>> it(a).take(2).to_list() 1288 ['a', 'b'] 1289 """ 1290 if n < 0: 1291 raise ValueError(f"Requested element count {n} is less than zero.") 1292 if n == 0: 1293 return Stream([]) 1294 from .take import TakeTransform 1295 1296 return it(TakeTransform(self, n))
Returns an Stream containing first [n] elements.
Example 1:
>>> a = ['a', 'b', 'c']
>>> it(a)pyiter.take(0).to_list()
[]
Example 2:
>>> a = ['a', 'b', 'c']
>>> it(a)pyiter.take(2).to_list()
['a', 'b']
1305 def take_while(self, predicate: Callable[..., bool]) -> Stream[T]: 1306 """ 1307 Returns an Stream containing first elements satisfying the given [predicate]. 1308 1309 Example 1: 1310 >>> lst = ['a', 'b', 'c', 'd'] 1311 >>> it(lst).take_while(lambda x: x in ['a', 'b']).to_list() 1312 ['a', 'b'] 1313 """ 1314 from .take_while import TakeWhileTransform 1315 1316 return it(TakeWhileTransform(self, self.__callback_overload_warpper__(predicate)))
Returns an Stream containing first elements satisfying the given [predicate].
Example 1:
>>> lst = ['a', 'b', 'c', 'd']
>>> it(lst)pyiter.take_while(lambda x: x in ['a', 'b']).to_list()
['a', 'b']
1325 def take_until(self, predicate: Callable[..., bool]) -> Stream[T]: 1326 """ 1327 Returns a Stream containing the first elements taken until the first element that satisfies the given [predicate]. 1328 1329 Example 1: 1330 >>> lst = [1, 2, 3, 4] 1331 >>> it(lst).take_until(lambda x: x > 2).to_list() 1332 [1, 2] 1333 1334 Example 2: 1335 >>> lst = [1, 2, 3, 4] 1336 >>> it(lst).take_until(lambda x: x > 10).to_list() 1337 [1, 2, 3, 4] 1338 """ 1339 from .take_until import TakeUntilTransform 1340 1341 return it(TakeUntilTransform(self, self.__callback_overload_warpper__(predicate)))
Returns a Stream containing the first elements taken until the first element that satisfies the given [predicate].
Example 1:
>>> lst = [1, 2, 3, 4]
>>> it(lst)pyiter.take_until(lambda x: x > 2).to_list()
[1, 2]
Example 2:
>>> lst = [1, 2, 3, 4]
>>> it(lst)pyiter.take_until(lambda x: x > 10).to_list()
[1, 2, 3, 4]
1343 def take_last(self, n: int) -> Stream[T]: 1344 """ 1345 Returns an Stream containing last [n] elements. 1346 1347 Example 1: 1348 >>> a = ['a', 'b', 'c'] 1349 >>> it(a).take_last(0).to_list() 1350 [] 1351 1352 Example 2: 1353 >>> a = ['a', 'b', 'c'] 1354 >>> it(a).take_last(2).to_list() 1355 ['b', 'c'] 1356 1357 Example 3: 1358 >>> a = ['a', 'b', 'c'] 1359 >>> it(a).take_last(10).to_list() 1360 ['a', 'b', 'c'] 1361 """ 1362 if n < 0: 1363 raise ValueError(f"Requested element count {n} is less than zero.") 1364 if n == 0: 1365 return Stream([]) 1366 1367 return self.drop(max(len(self) - n, 0))
Returns an Stream containing last [n] elements.
Example 1:
>>> a = ['a', 'b', 'c']
>>> it(a).take_last(0).to_list()
[]
Example 2:
>>> a = ['a', 'b', 'c']
>>> it(a).take_last(2).to_list()
['b', 'c']
Example 3:
>>> a = ['a', 'b', 'c']
>>> it(a).take_last(10).to_list()
['a', 'b', 'c']
1370 def sorted(self) -> Stream[T]: 1371 """ 1372 Returns an Stream that yields elements of this Stream sorted according to their natural sort order. 1373 1374 Example 1: 1375 >>> lst = ['b', 'a', 'e', 'c'] 1376 >>> it(lst).sorted().to_list() 1377 ['a', 'b', 'c', 'e'] 1378 1379 Example 2: 1380 >>> lst = [2, 1, 4, 3] 1381 >>> it(lst).sorted().to_list() 1382 [1, 2, 3, 4] 1383 """ 1384 lst = list(self) 1385 lst.sort() # type: ignore 1386 return it(lst)
Returns an Stream that yields elements of this Stream sorted according to their natural sort order.
Example 1:
>>> lst = ['b', 'a', 'e', 'c']
>>> it(lst).sorted().to_list()
['a', 'b', 'c', 'e']
Example 2:
>>> lst = [2, 1, 4, 3]
>>> it(lst).sorted().to_list()
[1, 2, 3, 4]
1397 def sorted_by(self, key_selector: Callable[..., SupportsRichComparisonT]) -> Stream[T]: 1398 """ 1399 Returns a sequence that yields elements of this sequence sorted according to natural sort 1400 order of the value returned by specified [key_selector] function. 1401 1402 Example 1: 1403 >>> lst = [ {'name': 'A', 'age': 12 }, {'name': 'C', 'age': 10 }, {'name': 'B', 'age': 11 } ] 1404 >>> it(lst).sorted_by(lambda x: x['name']).to_list() 1405 [{'name': 'A', 'age': 12}, {'name': 'B', 'age': 11}, {'name': 'C', 'age': 10}] 1406 >>> it(lst).sorted_by(lambda x: x['age']).to_list() 1407 [{'name': 'C', 'age': 10}, {'name': 'B', 'age': 11}, {'name': 'A', 'age': 12}] 1408 """ 1409 lst = list(self) 1410 lst.sort(key=self.__callback_overload_warpper__(key_selector)) 1411 return it(lst)
Returns a sequence that yields elements of this sequence sorted according to natural sort order of the value returned by specified [key_selector] function.
Example 1:
>>> lst = [ {'name': 'A', 'age': 12 }, {'name': 'C', 'age': 10 }, {'name': 'B', 'age': 11 } ]
>>> it(lst).sorted_by(lambda x: x['name']).to_list()
[{'name': 'A', 'age': 12}, {'name': 'B', 'age': 11}, {'name': 'C', 'age': 10}]
>>> it(lst).sorted_by(lambda x: x['age']).to_list()
[{'name': 'C', 'age': 10}, {'name': 'B', 'age': 11}, {'name': 'A', 'age': 12}]
1413 def sorted_descending(self) -> Stream[T]: 1414 """ 1415 Returns a Stream of all elements sorted descending according to their natural sort order. 1416 1417 Example 1: 1418 >>> lst = ['b', 'c', 'a'] 1419 >>> it(lst).sorted_descending().to_list() 1420 ['c', 'b', 'a'] 1421 """ 1422 return self.sorted().reversed()
Returns a Stream of all elements sorted descending according to their natural sort order.
Example 1:
>>> lst = ['b', 'c', 'a']
>>> it(lst).sorted_descending().to_list()
['c', 'b', 'a']
1436 def sorted_by_descending( 1437 self, key_selector: Callable[..., SupportsRichComparisonT] 1438 ) -> Stream[T]: 1439 """ 1440 Returns a sequence that yields elements of this sequence sorted descending according 1441 to natural sort order of the value returned by specified [key_selector] function. 1442 1443 Example 1: 1444 >>> lst = [ {'name': 'A', 'age': 12 }, {'name': 'C', 'age': 10 }, {'name': 'B', 'age': 11 } ] 1445 >>> it(lst).sorted_by_descending(lambda x: x['name']).to_list() 1446 [{'name': 'C', 'age': 10}, {'name': 'B', 'age': 11}, {'name': 'A', 'age': 12}] 1447 >>> it(lst).sorted_by_descending(lambda x: x['age']).to_list() 1448 [{'name': 'A', 'age': 12}, {'name': 'B', 'age': 11}, {'name': 'C', 'age': 10}] 1449 """ 1450 return self.sorted_by(key_selector).reversed()
Returns a sequence that yields elements of this sequence sorted descending according to natural sort order of the value returned by specified [key_selector] function.
Example 1:
>>> lst = [ {'name': 'A', 'age': 12 }, {'name': 'C', 'age': 10 }, {'name': 'B', 'age': 11 } ]
>>> it(lst).sorted_by_descending(lambda x: x['name']).to_list()
[{'name': 'C', 'age': 10}, {'name': 'B', 'age': 11}, {'name': 'A', 'age': 12}]
>>> it(lst).sorted_by_descending(lambda x: x['age']).to_list()
[{'name': 'A', 'age': 12}, {'name': 'B', 'age': 11}, {'name': 'C', 'age': 10}]
1453 def sorted_with(self, comparator: Callable[[T, T], int]) -> Stream[T]: 1454 """ 1455 Returns a sequence that yields elements of this sequence sorted according to the specified [comparator]. 1456 1457 Example 1: 1458 >>> lst = ['aa', 'bbb', 'c'] 1459 >>> it(lst).sorted_with(lambda a, b: len(a)-len(b)).to_list() 1460 ['c', 'aa', 'bbb'] 1461 """ 1462 from functools import cmp_to_key 1463 1464 lst = list(self) 1465 lst.sort(key=cmp_to_key(comparator)) 1466 return it(lst)
Returns a sequence that yields elements of this sequence sorted according to the specified [comparator].
Example 1:
>>> lst = ['aa', 'bbb', 'c']
>>> it(lst).sorted_with(lambda a, b: len(a)-len(b)).to_list()
['c', 'aa', 'bbb']
1474 def associate(self, transform: Callable[..., Tuple[K, V]]) -> Dict[K, V]: 1475 """ 1476 Returns a [Dict] containing key-value Tuple provided by [transform] function 1477 applied to elements of the given Stream. 1478 1479 Example 1: 1480 >>> lst = ['1', '2', '3'] 1481 >>> it(lst).associate(lambda x: (int(x), x)) 1482 {1: '1', 2: '2', 3: '3'} 1483 """ 1484 transform = self.__callback_overload_warpper__(transform) 1485 dic: Dict[K, V] = dict() 1486 for i in self: 1487 k, v = transform(i) 1488 dic[k] = v 1489 return dic
Returns a [Dict] containing key-value Tuple provided by [transform] function applied to elements of the given Stream.
Example 1:
>>> lst = ['1', '2', '3']
>>> it(lst).associate(lambda x: (int(x), x))
{1: '1', 2: '2', 3: '3'}
1501 def associate_by( 1502 self, 1503 key_selector: Callable[..., K], 1504 value_transform: Optional[Callable[[T], V]] = None, 1505 ) -> Union[Dict[K, T], Dict[K, V]]: 1506 """ 1507 Returns a [Dict] containing key-value Tuple provided by [transform] function 1508 applied to elements of the given Stream. 1509 1510 Example 1: 1511 >>> lst = ['1', '2', '3'] 1512 >>> it(lst).associate_by(lambda x: int(x)) 1513 {1: '1', 2: '2', 3: '3'} 1514 1515 Example 2: 1516 >>> lst = ['1', '2', '3'] 1517 >>> it(lst).associate_by(lambda x: int(x), lambda x: x+x) 1518 {1: '11', 2: '22', 3: '33'} 1519 1520 """ 1521 key_selector = self.__callback_overload_warpper__(key_selector) 1522 1523 dic: Dict[K, Any] = dict() 1524 for i in self: 1525 k = key_selector(i) 1526 dic[k] = i if value_transform is None else value_transform(i) 1527 return dic
Returns a [Dict] containing key-value Tuple provided by [transform] function applied to elements of the given Stream.
Example 1:
>>> lst = ['1', '2', '3']
>>> it(lst).associate_by(lambda x: int(x))
{1: '1', 2: '2', 3: '3'}
Example 2:
>>> lst = ['1', '2', '3']
>>> it(lst).associate_by(lambda x: int(x), lambda x: x+x)
{1: '11', 2: '22', 3: '33'}
1540 def associate_by_to( 1541 self, 1542 destination: Dict[K, Any], 1543 key_selector: Callable[[T], K], 1544 value_transform: Optional[Callable[[T], Any]] = None, 1545 ) -> Dict[K, Any]: 1546 """ 1547 Returns a [Dict] containing key-value Tuple provided by [transform] function 1548 applied to elements of the given Stream. 1549 1550 Example 1: 1551 >>> lst = ['1', '2', '3'] 1552 >>> it(lst).associate_by_to({}, lambda x: int(x)) 1553 {1: '1', 2: '2', 3: '3'} 1554 1555 Example 2: 1556 >>> lst = ['1', '2', '3'] 1557 >>> it(lst).associate_by_to({}, lambda x: int(x), lambda x: x+'!' ) 1558 {1: '1!', 2: '2!', 3: '3!'} 1559 1560 """ 1561 for i in self: 1562 k = key_selector(i) 1563 destination[k] = i if value_transform is None else value_transform(i) 1564 return destination
Returns a [Dict] containing key-value Tuple provided by [transform] function applied to elements of the given Stream.
Example 1:
>>> lst = ['1', '2', '3']
>>> it(lst).associate_by_to({}, lambda x: int(x))
{1: '1', 2: '2', 3: '3'}
Example 2:
>>> lst = ['1', '2', '3']
>>> it(lst).associate_by_to({}, lambda x: int(x), lambda x: x+'!' )
{1: '1!', 2: '2!', 3: '3!'}
1572 def all(self, predicate: Callable[..., bool]) -> bool: 1573 """ 1574 Returns True if all elements of the Stream satisfy the specified [predicate] function. 1575 1576 Example 1: 1577 >>> lst = [1, 2, 3] 1578 >>> it(lst).all(lambda x: x > 0) 1579 True 1580 >>> it(lst).all(lambda x: x > 1) 1581 False 1582 """ 1583 predicate = self.__callback_overload_warpper__(predicate) 1584 for i in self: 1585 if not predicate(i): 1586 return False 1587 return True
Returns True if all elements of the Stream satisfy the specified [predicate] function.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).all(lambda x: x > 0)
True
>>> it(lst).all(lambda x: x > 1)
False
1595 def any(self, predicate: Callable[..., bool]) -> bool: 1596 """ 1597 Returns True if any elements of the Stream satisfy the specified [predicate] function. 1598 1599 Example 1: 1600 >>> lst = [1, 2, 3] 1601 >>> it(lst).any(lambda x: x > 0) 1602 True 1603 >>> it(lst).any(lambda x: x > 3) 1604 False 1605 """ 1606 predicate = self.__callback_overload_warpper__(predicate) 1607 for i in self: 1608 if predicate(i): 1609 return True 1610 return False
Returns True if any elements of the Stream satisfy the specified [predicate] function.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).any(lambda x: x > 0)
True
>>> it(lst).any(lambda x: x > 3)
False
1620 def count(self, predicate: Optional[Callable[..., bool]] = None) -> int: 1621 """ 1622 Returns the number of elements in the Stream that satisfy the specified [predicate] function. 1623 1624 Example 1: 1625 >>> lst = [1, 2, 3] 1626 >>> it(lst).count() 1627 3 1628 >>> it(lst).count(lambda x: x > 0) 1629 3 1630 >>> it(lst).count(lambda x: x > 2) 1631 1 1632 """ 1633 if predicate is None: 1634 return len(self) 1635 predicate = self.__callback_overload_warpper__(predicate) 1636 return sum(1 for i in self if predicate(i))
Returns the number of elements in the Stream that satisfy the specified [predicate] function.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).count()
3
>>> it(lst).count(lambda x: x > 0)
3
>>> it(lst).count(lambda x: x > 2)
1
1638 def contains(self, value: T) -> bool: 1639 """ 1640 Returns True if the Stream contains the specified [value]. 1641 1642 Example 1: 1643 >>> lst = [1, 2, 3] 1644 >>> it(lst).contains(1) 1645 True 1646 >>> it(lst).contains(4) 1647 False 1648 """ 1649 return value in self
Returns True if the Stream contains the specified [value].
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).contains(1)
True
>>> it(lst).contains(4)
False
1651 def element_at(self, index: int) -> T: 1652 """ 1653 Returns the element at the specified [index] in the Stream. 1654 1655 Example 1: 1656 >>> lst = [1, 2, 3] 1657 >>> it(lst).element_at(1) 1658 2 1659 1660 Example 2: 1661 >>> lst = [1, 2, 3] 1662 >>> it(lst).element_at(3) 1663 Traceback (most recent call last): 1664 ... 1665 IndexError: Index 3 out of range 1666 """ 1667 return self.element_at_or_else( 1668 index, lambda index: throw(IndexError(f"Index {index} out of range")) 1669 )
Returns the element at the specified [index] in the Stream.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).element_at(1)
2
Example 2:
>>> lst = [1, 2, 3]
>>> it(lst).element_at(3)
Traceback (most recent call last):
...
IndexError: Index 3 out of range
1689 def element_at_or_else( 1690 self, index: int, default: Union[Callable[[int], T], T, None] = None 1691 ) -> Optional[T]: 1692 """ 1693 Returns the element at the specified [index] in the Stream or the [default] value if the index is out of bounds. 1694 1695 Example 1: 1696 >>> lst = [1, 2, 3] 1697 >>> it(lst).element_at_or_else(1, lambda x: 'default') 1698 2 1699 >>> it(lst).element_at_or_else(4, lambda x: 'default') 1700 'default' 1701 1702 """ 1703 if index >= 0: 1704 if ( 1705 isinstance(self.__transform__, NonTransform) 1706 and isinstance(self.__transform__.iter, list) 1707 and index < len(self.__transform__.iter) 1708 ): 1709 return self.__transform__.iter[index] 1710 for i, e in enumerate(self): 1711 if i == index: 1712 return e 1713 return default(index) if callable(default) else default # type: ignore
Returns the element at the specified [index] in the Stream or the [default] value if the index is out of bounds.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).element_at_or_else(1, lambda x: 'default')
2
>>> it(lst).element_at_or_else(4, lambda x: 'default')
'default'
1715 def element_at_or_default(self, index: int, default: T) -> T: 1716 """ 1717 Returns the element at the specified [index] in the Stream or the [default] value if the index is out of bounds. 1718 1719 Example 1: 1720 >>> lst = [1, 2, 3] 1721 >>> it(lst).element_at_or_default(1, 'default') 1722 2 1723 >>> it(lst).element_at_or_default(4, 'default') 1724 'default' 1725 1726 """ 1727 return self.element_at_or_else(index, default)
Returns the element at the specified [index] in the Stream or the [default] value if the index is out of bounds.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).element_at_or_default(1, 'default')
2
>>> it(lst).element_at_or_default(4, 'default')
'default'
1729 def element_at_or_none(self, index: int) -> Optional[T]: 1730 """ 1731 Returns the element at the specified [index] in the Stream or None if the index is out of bounds. 1732 1733 Example 1: 1734 >>> lst = [1, 2, 3] 1735 >>> it(lst).element_at_or_none(1) 1736 2 1737 >>> it(lst).element_at_or_none(4) is None 1738 True 1739 """ 1740 return self.element_at_or_else(index)
Returns the element at the specified [index] in the Stream or None if the index is out of bounds.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).element_at_or_none(1)
2
>>> it(lst).element_at_or_none(4) is None
True
1742 def distinct(self) -> Stream[T]: 1743 """ 1744 Returns a new Stream containing the distinct elements of the given Stream. 1745 1746 Example 1: 1747 >>> lst = [1, 2, 3, 1, 2, 3] 1748 >>> it(lst).distinct().to_list() 1749 [1, 2, 3] 1750 1751 Example 2: 1752 >>> lst = [(1, 'A'), (1, 'A'), (1, 'A'), (2, 'A'), (3, 'C'), (3, 'D')] 1753 >>> it(lst).distinct().sorted().to_list() 1754 [(1, 'A'), (2, 'A'), (3, 'C'), (3, 'D')] 1755 1756 """ 1757 from .distinct import DistinctTransform 1758 1759 return it(DistinctTransform(self))
Returns a new Stream containing the distinct elements of the given Stream.
Example 1:
>>> lst = [1, 2, 3, 1, 2, 3]
>>> it(lst)pyiter.distinct().to_list()
[1, 2, 3]
Example 2:
>>> lst = [(1, 'A'), (1, 'A'), (1, 'A'), (2, 'A'), (3, 'C'), (3, 'D')]
>>> it(lst)pyiter.distinct().sorted().to_list()
[(1, 'A'), (2, 'A'), (3, 'C'), (3, 'D')]
1767 def distinct_by(self, key_selector: Callable[..., Any]) -> Stream[T]: 1768 """ 1769 Returns a new Stream containing the distinct elements of the given Stream. 1770 1771 Example 1: 1772 >>> lst = [1, 2, 3, 1, 2, 3] 1773 >>> it(lst).distinct_by(lambda x: x%2).to_list() 1774 [1, 2] 1775 """ 1776 from .distinct import DistinctTransform 1777 1778 return it(DistinctTransform(self, self.__callback_overload_warpper__(key_selector)))
Returns a new Stream containing the distinct elements of the given Stream.
Example 1:
>>> lst = [1, 2, 3, 1, 2, 3]
>>> it(lst).distinct_by(lambda x: x%2).to_list()
[1, 2]
1784 def reduce(self, accumulator: Callable[..., U], initial: Optional[U] = None) -> Optional[U]: 1785 """ 1786 Returns the result of applying the specified [accumulator] function to the given Stream's elements. 1787 1788 Example 1: 1789 >>> lst = [1, 2, 3] 1790 >>> it(lst).reduce(lambda x, y: x+y) 1791 6 1792 """ 1793 result: Optional[U] = initial 1794 for i, e in enumerate(self): 1795 if i == 0 and initial is None: 1796 result = e # type: ignore 1797 continue 1798 1799 result = accumulator(result, e) 1800 return result
Returns the result of applying the specified [accumulator] function to the given Stream's elements.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).reduce(lambda x, y: x+y)
6
1802 def fold(self, initial: U, accumulator: Callable[[U, T], U]) -> U: 1803 """ 1804 Returns the result of applying the specified [accumulator] function to the given Stream's elements. 1805 1806 Example 1: 1807 >>> lst = [1, 2, 3] 1808 >>> it(lst).fold(0, lambda x, y: x+y) 1809 6 1810 """ 1811 return self.reduce(accumulator, initial)
Returns the result of applying the specified [accumulator] function to the given Stream's elements.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).fold(0, lambda x, y: x+y)
6
1817 def sum_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]: 1818 """ 1819 Returns the sum of the elements of the given Stream. 1820 1821 Example 1: 1822 >>> lst = [1, 2, 3] 1823 >>> it(lst).sum_of(lambda x: x) 1824 6 1825 """ 1826 return sum(selector(i) for i in self)
Returns the sum of the elements of the given Stream.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).sum_of(lambda x: x)
6
1832 def max_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]: 1833 """ 1834 Returns the maximum element of the given Stream. 1835 1836 Example 1: 1837 >>> lst = [1, 2, 3] 1838 >>> it(lst).max_of(lambda x: x) 1839 3 1840 """ 1841 return max(selector(i) for i in self)
Returns the maximum element of the given Stream.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).max_of(lambda x: x)
3
1847 def max_by_or_none(self, selector: Callable[[T], Union[float, int]]) -> Optional[T]: 1848 """ 1849 Returns the first element yielding the largest value of the given function 1850 or `none` if there are no elements. 1851 1852 Example 1: 1853 >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }] 1854 >>> it(lst).max_by_or_none(lambda x: x["num"]) 1855 {'name': 'B', 'num': 200} 1856 1857 Example 2: 1858 >>> lst = [] 1859 >>> it(lst).max_by_or_none(lambda x: x["num"]) 1860 """ 1861 1862 max_item = None 1863 max_val = None 1864 1865 for item in self: 1866 val = selector(item) 1867 if max_val is None or val > max_val: 1868 max_item = item 1869 max_val = val 1870 1871 return max_item
Returns the first element yielding the largest value of the given function
or none if there are no elements.
Example 1:
>>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
>>> it(lst).max_by_or_none(lambda x: x["num"])
{'name': 'B', 'num': 200}
Example 2:
>>> lst = []
>>> it(lst).max_by_or_none(lambda x: x["num"])
1877 def max_by(self, selector: Callable[[T], Union[float, int]]) -> T: 1878 """ 1879 Returns the first element yielding the largest value of the given function. 1880 1881 Example 1: 1882 >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }] 1883 >>> it(lst).max_by(lambda x: x["num"]) 1884 {'name': 'B', 'num': 200} 1885 1886 Exmaple 2: 1887 >>> lst = [] 1888 >>> it(lst).max_by(lambda x: x["num"]) 1889 Traceback (most recent call last): 1890 ... 1891 ValueError: Stream is empty. 1892 """ 1893 max_item = self.max_by_or_none(selector) 1894 if max_item is None: 1895 raise ValueError("Stream is empty.") 1896 return max_item
Returns the first element yielding the largest value of the given function.
Example 1:
>>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
>>> it(lst).max_by(lambda x: x["num"])
{'name': 'B', 'num': 200}
Exmaple 2:
>>> lst = []
>>> it(lst).max_by(lambda x: x["num"])
Traceback (most recent call last):
...
ValueError: Stream is empty.
1912 def min_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]: 1913 return min(selector(i) for i in self)
Returns the minimum element of the given Stream.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).min_of(lambda x: x)
1
1919 def min_by_or_none(self, selector: Callable[[T], float]) -> Optional[T]: 1920 """ 1921 Returns the first element yielding the smallest value of the given function 1922 or `none` if there are no elements. 1923 1924 Example 1: 1925 >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }] 1926 >>> it(lst).min_by_or_none(lambda x: x["num"]) 1927 {'name': 'A', 'num': 100} 1928 1929 Exmaple 2: 1930 >>> lst = [] 1931 >>> it(lst).min_by_or_none(lambda x: x["num"]) 1932 """ 1933 min_item = None 1934 min_val = None 1935 1936 for item in self: 1937 val = selector(item) 1938 if min_val is None or val < min_val: 1939 min_item = item 1940 min_val = val 1941 1942 return min_item
Returns the first element yielding the smallest value of the given function
or none if there are no elements.
Example 1:
>>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
>>> it(lst).min_by_or_none(lambda x: x["num"])
{'name': 'A', 'num': 100}
Exmaple 2:
>>> lst = []
>>> it(lst).min_by_or_none(lambda x: x["num"])
1948 def min_by(self, selector: Callable[[T], float]) -> T: 1949 """ 1950 Returns the first element yielding the smallest value of the given function. 1951 1952 Example 1: 1953 >>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }] 1954 >>> it(lst).min_by(lambda x: x["num"]) 1955 {'name': 'A', 'num': 100} 1956 1957 Exmaple 2: 1958 >>> lst = [] 1959 >>> it(lst).min_by(lambda x: x["num"]) 1960 Traceback (most recent call last): 1961 ... 1962 ValueError: Stream is empty. 1963 """ 1964 min_item = self.min_by_or_none(selector) 1965 if min_item is None: 1966 raise ValueError("Stream is empty.") 1967 1968 return min_item
Returns the first element yielding the smallest value of the given function.
Example 1:
>>> lst = [ { "name": "A", "num": 100 }, { "name": "B", "num": 200 }]
>>> it(lst).min_by(lambda x: x["num"])
{'name': 'A', 'num': 100}
Exmaple 2:
>>> lst = []
>>> it(lst).min_by(lambda x: x["num"])
Traceback (most recent call last):
...
ValueError: Stream is empty.
1970 def mean_of(self, selector: Callable[[T], Union[int, float]]) -> Union[int, float]: 1971 """ 1972 Returns the mean of the elements of the given Stream. 1973 1974 Example 1: 1975 >>> lst = [1, 2, 3] 1976 >>> it(lst).mean_of(lambda x: x) 1977 2.0 1978 """ 1979 return self.sum_of(selector) / len(self)
Returns the mean of the elements of the given Stream.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).mean_of(lambda x: x)
2.0
1995 def sum(self: Union[Stream[int], Stream[float]]) -> Union[float, int]: 1996 """ 1997 Returns the sum of the elements of the given Stream. 1998 1999 Example 1: 2000 >>> lst = [1, 2, 3] 2001 >>> it(lst).sum() 2002 6 2003 """ 2004 return sum(self)
Returns the sum of the elements of the given Stream.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).sum()
6
2010 def max(self: Union[Stream[int], Stream[float]]) -> Union[float, int]: 2011 """ 2012 Returns the maximum element of the given Stream. 2013 2014 Example 1: 2015 >>> lst = [1, 2, 3] 2016 >>> it(lst).max() 2017 3 2018 """ 2019 return max(self)
Returns the maximum element of the given Stream.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).max()
3
2029 def max_or_default( 2030 self: Union[Stream[int], Stream[float]], default: Optional[V] = None 2031 ) -> Union[float, int, V, None]: 2032 """ 2033 Returns the maximum element of the given Stream. 2034 2035 Example 1: 2036 >>> lst = [1, 2, 3] 2037 >>> it(lst).max_or_default() 2038 3 2039 2040 Example 2: 2041 >>> lst = [] 2042 >>> it(lst).max_or_default() is None 2043 True 2044 2045 Example 3: 2046 >>> lst = [] 2047 >>> it(lst).max_or_default(9) 2048 9 2049 """ 2050 if self.is_empty(): 2051 return default 2052 return max(self)
Returns the maximum element of the given Stream.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).max_or_default()
3
Example 2:
>>> lst = []
>>> it(lst).max_or_default() is None
True
Example 3:
>>> lst = []
>>> it(lst).max_or_default(9)
9
2058 def max_or_none( 2059 self: Union[Stream[int], Stream[float]], 2060 ) -> Union[float, int, None]: 2061 """ 2062 Returns the maximum element of the given Stream. 2063 2064 Example 1: 2065 >>> lst = [1, 2, 3] 2066 >>> it(lst).max_or_none() 2067 3 2068 2069 Example 2: 2070 >>> lst = [] 2071 >>> it(lst).max_or_none() is None 2072 True 2073 """ 2074 return self.max_or_default(None)
Returns the maximum element of the given Stream.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).max_or_none()
3
Example 2:
>>> lst = []
>>> it(lst).max_or_none() is None
True
2090 def min(self: Union[Stream[int], Stream[float]]) -> Union[float, int]: 2091 """ 2092 Returns the minimum element of the given Stream. 2093 2094 Example 1: 2095 >>> lst = [1, 2, 3] 2096 >>> it(lst).min() 2097 1 2098 """ 2099 return min(self)
Returns the minimum element of the given Stream.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).min()
1
2115 def min_or_none( 2116 self: Union[Stream[int], Stream[float]], 2117 ) -> Union[float, int, None]: 2118 """ 2119 Returns the minimum element of the given Stream. 2120 2121 Example 1: 2122 >>> lst = [1, 2, 3] 2123 >>> it(lst).min_or_none() 2124 1 2125 """ 2126 return self.min_or_default(None)
Returns the minimum element of the given Stream.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).min_or_none()
1
2146 def min_or_default( 2147 self: Union[Stream[int], Stream[float]], default: Optional[V] = None 2148 ) -> Union[float, int, V, None]: 2149 """ 2150 Returns the minimum element of the given Stream. 2151 2152 Example 1: 2153 >>> lst = [1, 2, 3] 2154 >>> it(lst).min_or_default() 2155 1 2156 2157 Example 2: 2158 >>> lst = [] 2159 >>> it(lst).min_or_default(9) 2160 9 2161 """ 2162 if self.is_empty(): 2163 return default 2164 return min(self)
Returns the minimum element of the given Stream.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).min_or_default()
1
Example 2:
>>> lst = []
>>> it(lst).min_or_default(9)
9
2180 def mean(self: Union[Stream[int], Stream[float]]) -> float: 2181 """ 2182 Returns the mean of the elements of the given Stream. 2183 2184 Example 1: 2185 >>> lst = [1, 2, 3] 2186 >>> it(lst).mean() 2187 2.0 2188 """ 2189 return self.sum() / len(self)
Returns the mean of the elements of the given Stream.
Example 1:
>>> lst = [1, 2, 3]
>>> it(lst).mean()
2.0
2192 def reversed(self) -> Stream[T]: 2193 """ 2194 Returns a list with elements in reversed order. 2195 2196 Example 1: 2197 >>> lst = ['b', 'c', 'a'] 2198 >>> it(lst).reversed().to_list() 2199 ['a', 'c', 'b'] 2200 """ 2201 lst = list(self) 2202 lst.reverse() 2203 return it(lst)
Returns a list with elements in reversed order.
Example 1:
>>> lst = ['b', 'c', 'a']
>>> it(lst).reversed().to_list()
['a', 'c', 'b']
2211 def flat_map(self, transform: Callable[..., Iterable[U]]) -> Stream[U]: 2212 """ 2213 Returns a single list of all elements yielded from results of [transform] 2214 function being invoked on each element of original collection. 2215 2216 Example 1: 2217 >>> lst = [['a', 'b'], ['c'], ['d', 'e']] 2218 >>> it(lst).flat_map(lambda x: x).to_list() 2219 ['a', 'b', 'c', 'd', 'e'] 2220 """ 2221 return self.map(transform).flatten()
Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original collection.
Example 1:
>>> lst = [['a', 'b'], ['c'], ['d', 'e']]
>>> it(lst).flat_map(lambda x: x).to_list()
['a', 'b', 'c', 'd', 'e']
2223 def flatten(self: Iterable[Iterable[U]]) -> Stream[U]: 2224 """ 2225 Returns a sequence of all elements from all sequences in this sequence. 2226 2227 Example 1: 2228 >>> lst = [['a', 'b'], ['c'], ['d', 'e']] 2229 >>> it(lst).flatten().to_list() 2230 ['a', 'b', 'c', 'd', 'e'] 2231 """ 2232 from .flattening import FlatteningTransform 2233 2234 return it(FlatteningTransform(self))
Returns a sequence of all elements from all sequences in this sequence.
Example 1:
>>> lst = [['a', 'b'], ['c'], ['d', 'e']]
>>> it(lst).flatten().to_list()
['a', 'b', 'c', 'd', 'e']
2244 def group_by(self, key_selector: Callable[..., K]) -> Stream[Grouping[K, T]]: 2245 """ 2246 Returns a dictionary with keys being the result of [key_selector] function being invoked on each element of original collection 2247 and values being the corresponding elements of original collection. 2248 2249 Example 1: 2250 >>> lst = [1, 2, 3, 4, 5] 2251 >>> it(lst).group_by(lambda x: x%2).map(lambda x: (x.key, x.values.to_list())).to_list() 2252 [(1, [1, 3, 5]), (0, [2, 4])] 2253 """ 2254 from .grouping import GroupingTransform 2255 2256 return it(GroupingTransform(self, self.__callback_overload_warpper__(key_selector)))
Returns a dictionary with keys being the result of [key_selector] function being invoked on each element of original collection and values being the corresponding elements of original collection.
Example 1:
>>> lst = [1, 2, 3, 4, 5]
>>> it(lst).group_by(lambda x: x%2).map(lambda x: (x.key, x.values.to_list())).to_list()
[(1, [1, 3, 5]), (0, [2, 4])]
2272 def group_by_to( 2273 self, destination: Dict[K, List[T]], key_selector: Callable[..., K] 2274 ) -> Dict[K, List[T]]: 2275 """ 2276 Returns a dictionary with keys being the result of [key_selector] function being invoked on each element of original collection 2277 and values being the corresponding elements of original collection. 2278 2279 Example 1: 2280 >>> lst = [1, 2, 3, 4, 5] 2281 >>> it(lst).group_by_to({}, lambda x: x%2) 2282 {1: [1, 3, 5], 0: [2, 4]} 2283 """ 2284 key_selector = self.__callback_overload_warpper__(key_selector) 2285 for e in self: 2286 k = key_selector(e) 2287 if k not in destination: 2288 destination[k] = [] 2289 destination[k].append(e) 2290 return destination
Returns a dictionary with keys being the result of [key_selector] function being invoked on each element of original collection and values being the corresponding elements of original collection.
Example 1:
>>> lst = [1, 2, 3, 4, 5]
>>> it(lst).group_by_to({}, lambda x: x%2)
{1: [1, 3, 5], 0: [2, 4]}
2298 def for_each(self, action: Callable[..., None]) -> None: 2299 """ 2300 Invokes [action] function on each element of the given Stream. 2301 2302 Example 1: 2303 >>> lst = ['a', 'b', 'c'] 2304 >>> it(lst).for_each(lambda x: print(x)) 2305 a 2306 b 2307 c 2308 2309 Example 2: 2310 >>> lst = ['a', 'b', 'c'] 2311 >>> it(lst).for_each(lambda x, i: print(x, i)) 2312 a 0 2313 b 1 2314 c 2 2315 """ 2316 self.on_each(action)
Invokes [action] function on each element of the given Stream.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).for_each(lambda x: print(x))
a
b
c
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).for_each(lambda x, i: print(x, i))
a 0
b 1
c 2
2332 def parallel_for_each( 2333 self, action: Callable[..., None], max_workers: Optional[int] = None 2334 ) -> None: 2335 """ 2336 Invokes [action] function on each element of the given Stream in parallel. 2337 2338 Example 1: 2339 >>> lst = ['a', 'b', 'c'] 2340 >>> it(lst).parallel_for_each(lambda x: print(x)) 2341 a 2342 b 2343 c 2344 2345 Example 2: 2346 >>> lst = ['a', 'b', 'c'] 2347 >>> it(lst).parallel_for_each(lambda x: print(x), max_workers=2) 2348 a 2349 b 2350 c 2351 """ 2352 self.parallel_on_each(action, max_workers)
Invokes [action] function on each element of the given Stream in parallel.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).parallel_for_each(lambda x: print(x))
a
b
c
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).parallel_for_each(lambda x: print(x), max_workers=2)
a
b
c
2360 def on_each(self, action: Callable[..., None]) -> Stream[T]: 2361 """ 2362 Invokes [action] function on each element of the given Stream. 2363 2364 Example 1: 2365 >>> lst = ['a', 'b', 'c'] 2366 >>> it(lst).on_each(lambda x: print(x)) and None 2367 a 2368 b 2369 c 2370 2371 Example 2: 2372 >>> lst = ['a', 'b', 'c'] 2373 >>> it(lst).on_each(lambda x, i: print(x, i)) and None 2374 a 0 2375 b 1 2376 c 2 2377 """ 2378 action = self.__callback_overload_warpper__(action) 2379 for i in self: 2380 action(i) 2381 return self
Invokes [action] function on each element of the given Stream.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).on_each(lambda x: print(x)) and None
a
b
c
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).on_each(lambda x, i: print(x, i)) and None
a 0
b 1
c 2
2407 def parallel_on_each( 2408 self, 2409 action: Callable[..., None], 2410 max_workers: Optional[int] = None, 2411 chunksize: int = 1, 2412 executor: "ParallelMappingTransform.Executor" = "Thread", 2413 ) -> Stream[T]: 2414 """ 2415 Invokes [action] function on each element of the given Stream. 2416 2417 Example 1: 2418 >>> lst = ['a', 'b', 'c'] 2419 >>> it(lst).parallel_on_each(lambda x: print(x)) and None 2420 a 2421 b 2422 c 2423 2424 Example 2: 2425 >>> lst = ['a', 'b', 'c'] 2426 >>> it(lst).parallel_on_each(lambda x: print(x), max_workers=2) and None 2427 a 2428 b 2429 c 2430 """ 2431 from .parallel_mapping import ParallelMappingTransform 2432 2433 action = self.__callback_overload_warpper__(action) 2434 for _ in ParallelMappingTransform(self, action, max_workers, chunksize, executor): 2435 pass 2436 return self
Invokes [action] function on each element of the given Stream.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).parallel_on_each(lambda x: print(x)) and None
a
b
c
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).parallel_on_each(lambda x: print(x), max_workers=2) and None
a
b
c
2442 def zip( 2443 self, 2444 other: Iterable[Any], 2445 transform: Optional[Callable[..., V]] = None, # type: ignore 2446 ) -> Stream[Any]: 2447 """ 2448 Returns a new Stream of tuples, where each tuple contains two elements. 2449 2450 Example 1: 2451 >>> lst1 = ['a', 'b', 'c'] 2452 >>> lst2 = [1, 2, 3] 2453 >>> it(lst1).zip(lst2).to_list() 2454 [('a', 1), ('b', 2), ('c', 3)] 2455 2456 Example 2: 2457 >>> lst1 = ['a', 'b', 'c'] 2458 >>> lst2 = [1, 2, 3] 2459 >>> it(lst1).zip(lst2, lambda x, y: x + '__' +str( y)).to_list() 2460 ['a__1', 'b__2', 'c__3'] 2461 """ 2462 if transform is None: 2463 2464 def transform(*x: Any) -> Tuple[Any, ...]: 2465 return (*x,) 2466 2467 from .merging import MergingTransform 2468 2469 return it(MergingTransform(self, other, transform))
Returns a new Stream of tuples, where each tuple contains two elements.
Example 1:
>>> lst1 = ['a', 'b', 'c']
>>> lst2 = [1, 2, 3]
>>> it(lst1).zip(lst2).to_list()
[('a', 1), ('b', 2), ('c', 3)]
Example 2:
>>> lst1 = ['a', 'b', 'c']
>>> lst2 = [1, 2, 3]
>>> it(lst1).zip(lst2, lambda x, y: x + '__' +str( y)).to_list()
['a__1', 'b__2', 'c__3']
2475 def zip_with_next(self, transform: Optional[Callable[[T, T], Any]] = None) -> Stream[Any]: 2476 """ 2477 Returns a sequence containing the results of applying the given [transform] function 2478 to an each pair of two adjacent elements in this sequence. 2479 2480 Example 1: 2481 >>> lst = ['a', 'b', 'c'] 2482 >>> it(lst).zip_with_next(lambda x, y: x + '__' + y).to_list() 2483 ['a__b', 'b__c'] 2484 2485 Example 2: 2486 >>> lst = ['a', 'b', 'c'] 2487 >>> it(lst).zip_with_next().to_list() 2488 [('a', 'b'), ('b', 'c')] 2489 """ 2490 from .merging_with_next import MergingWithNextTransform 2491 2492 return it(MergingWithNextTransform(self, transform or (lambda a, b: (a, b))))
Returns a sequence containing the results of applying the given [transform] function to an each pair of two adjacent elements in this sequence.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).zip_with_next(lambda x, y: x + '__' + y).to_list()
['a__b', 'b__c']
Example 2:
>>> lst = ['a', 'b', 'c']
>>> it(lst).zip_with_next().to_list()
[('a', 'b'), ('b', 'c')]
2506 def unzip( # type: ignore 2507 self: Stream[Tuple[U, V]], 2508 transform: Union[Optional[Callable[..., Tuple[Any, Any]]], bool] = None, 2509 ) -> "Tuple[ListLike[U], ListLike[V]]": 2510 """ 2511 Returns a pair of lists, where first list is built from the first values of each pair from this array, second list is built from the second values of each pair from this array. 2512 2513 Example 1: 2514 >>> lst = [{'name': 'a', 'age': 11}, {'name': 'b', 'age': 12}, {'name': 'c', 'age': 13}] 2515 >>> a, b = it(lst).unzip(lambda x: (x['name'], x['age'])) 2516 >>> a 2517 ['a', 'b', 'c'] 2518 >>> b 2519 [11, 12, 13] 2520 2521 Example 1: 2522 >>> lst = [('a', 11), ('b', 12), ('c', 13)] 2523 >>> a, b = it(lst).unzip() 2524 >>> a 2525 ['a', 'b', 'c'] 2526 >>> b 2527 [11, 12, 13] 2528 """ 2529 from .list_like import ListLike 2530 2531 it = self 2532 if isinstance(transform, bool): 2533 transform = None 2534 2535 if transform is not None: 2536 transform = self.__callback_overload_warpper__(transform) 2537 it = it.map(transform) 2538 2539 a = it.map(lambda x: x[0]) # type: ignore 2540 b = it.map(lambda x: x[1]) # type: ignore 2541 2542 return ListLike(a), ListLike(b)
Returns a pair of lists, where first list is built from the first values of each pair from this array, second list is built from the second values of each pair from this array.
Example 1:
>>> lst = [{'name': 'a', 'age': 11}, {'name': 'b', 'age': 12}, {'name': 'c', 'age': 13}]
>>> a, b = it(lst).unzip(lambda x: (x['name'], x['age']))
>>> a
['a', 'b', 'c']
>>> b
[11, 12, 13]
Example 1:
>>> lst = [('a', 11), ('b', 12), ('c', 13)]
>>> a, b = it(lst).unzip()
>>> a
['a', 'b', 'c']
>>> b
[11, 12, 13]
2544 def with_index(self) -> Stream[IndexedValue[T]]: 2545 """ 2546 Returns a sequence containing the elements of this sequence and their indexes. 2547 2548 Example 1: 2549 >>> lst = ['a', 'b', 'c'] 2550 >>> it(lst).with_index().to_list() 2551 [IndexedValue(0, a), IndexedValue(1, b), IndexedValue(2, c)] 2552 """ 2553 return self.indexed()
Returns a sequence containing the elements of this sequence and their indexes.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).with_index().to_list()
[IndexedValue(0, a), IndexedValue(1, b), IndexedValue(2, c)]
2561 def shuffled( # type: ignore 2562 self, seed: Union["Random", int, float, str, bytes, bytearray, None] = None 2563 ) -> Stream[T]: 2564 """ 2565 Returns a sequence that yields elements of this sequence randomly shuffled 2566 using the specified [random] instance as the source of randomness. 2567 2568 Example 1: 2569 >>> lst = ['a', 'b', 'c'] 2570 >>> it(lst).shuffled('123').to_list() 2571 ['b', 'a', 'c'] 2572 2573 Example 2: 2574 >>> from random import Random 2575 >>> lst = ['a', 'b', 'c'] 2576 >>> it(lst).shuffled(Random('123')).to_list() 2577 ['b', 'a', 'c'] 2578 2579 Example 3: 2580 >>> lst = ['a', 'b', 'c'] 2581 >>> it(lst).shuffled(123).to_list() 2582 ['c', 'b', 'a'] 2583 """ 2584 from .shuffling import ShufflingTransform 2585 2586 return it(ShufflingTransform(self, seed))
Returns a sequence that yields elements of this sequence randomly shuffled using the specified [random] instance as the source of randomness.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).shuffled('123').to_list()
['b', 'a', 'c']
Example 2:
>>> from random import Random
>>> lst = ['a', 'b', 'c']
>>> it(lst).shuffled(Random('123')).to_list()
['b', 'a', 'c']
Example 3:
>>> lst = ['a', 'b', 'c']
>>> it(lst).shuffled(123).to_list()
['c', 'b', 'a']
2598 def partition(self, predicate: Callable[..., bool]) -> "Tuple[ListLike[T], ListLike[T]]": 2599 """ 2600 Partitions the elements of the given Stream into two groups, 2601 the first group containing the elements for which the predicate returns true, 2602 and the second containing the rest. 2603 2604 Example 1: 2605 >>> lst = ['a', 'b', 'c', '2'] 2606 >>> it(lst).partition(lambda x: x.isalpha()) 2607 (['a', 'b', 'c'], ['2']) 2608 2609 Example 2: 2610 >>> lst = ['a', 'b', 'c', '2'] 2611 >>> it(lst).partition(lambda _, i: i % 2 == 0) 2612 (['a', 'c'], ['b', '2']) 2613 """ 2614 from .list_like import ListLike 2615 2616 predicate_a = self.__callback_overload_warpper__(predicate) 2617 predicate_b = self.__callback_overload_warpper__(predicate) 2618 part_a = self.filter(predicate_a) 2619 part_b = self.filter(lambda x: not predicate_b(x)) 2620 return ListLike(part_a), ListLike(part_b)
Partitions the elements of the given Stream into two groups, the first group containing the elements for which the predicate returns true, and the second containing the rest.
Example 1:
>>> lst = ['a', 'b', 'c', '2']
>>> it(lst).partition(lambda x: x.isalpha())
(['a', 'b', 'c'], ['2'])
Example 2:
>>> lst = ['a', 'b', 'c', '2']
>>> it(lst).partition(lambda _, i: i % 2 == 0)
(['a', 'c'], ['b', '2'])
2633 def combinations(self, n: int) -> Stream[Tuple[T, ...]]: 2634 """ 2635 Returns a Stream of all possible combinations of size [n] from the given Stream. 2636 2637 Example 1: 2638 >>> lst = ['a', 'b', 'c'] 2639 >>> it(lst).combinations(2).to_list() 2640 [('a', 'b'), ('a', 'c'), ('b', 'c')] 2641 """ 2642 from .combination import CombinationTransform 2643 2644 return it(CombinationTransform(self, n))
Returns a Stream of all possible combinations of size [n] from the given Stream.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).combinations(2).to_list()
[('a', 'b'), ('a', 'c'), ('b', 'c')]
2646 def nth(self, n: int) -> T: 2647 """ 2648 Returns the nth element of the given Stream. 2649 2650 Example 1: 2651 >>> lst = ['a', 'b', 'c'] 2652 >>> it(lst).nth(2) 2653 'c' 2654 """ 2655 return self.skip(n).first()
Returns the nth element of the given Stream.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).nth(2)
'c'
2657 def windowed(self, size: int, step: int = 1, partialWindows: bool = False) -> Stream[List[T]]: 2658 """ 2659 Returns a Stream of all possible sliding windows of size [size] from the given Stream. 2660 2661 Example 1: 2662 >>> lst = ['a', 'b', 'c', 'd', 'e'] 2663 >>> it(lst).windowed(3).to_list() 2664 [['a', 'b', 'c'], ['b', 'c', 'd'], ['c', 'd', 'e']] 2665 2666 Example 2: 2667 >>> lst = ['a', 'b', 'c', 'd', 'e'] 2668 >>> it(lst).windowed(3, 2).to_list() 2669 [['a', 'b', 'c'], ['c', 'd', 'e']] 2670 2671 Example 3: 2672 >>> lst = ['a', 'b', 'c', 'd', 'e', 'f'] 2673 >>> it(lst).windowed(3, 2, True).to_list() 2674 [['a', 'b', 'c'], ['c', 'd', 'e'], ['e', 'f']] 2675 """ 2676 from .windowed import WindowedTransform 2677 2678 return it(WindowedTransform(self, size, step, partialWindows))
Returns a Stream of all possible sliding windows of size [size] from the given Stream.
Example 1:
>>> lst = ['a', 'b', 'c', 'd', 'e']
>>> it(lst)pyiter.windowed(3).to_list()
[['a', 'b', 'c'], ['b', 'c', 'd'], ['c', 'd', 'e']]
Example 2:
>>> lst = ['a', 'b', 'c', 'd', 'e']
>>> it(lst)pyiter.windowed(3, 2).to_list()
[['a', 'b', 'c'], ['c', 'd', 'e']]
Example 3:
>>> lst = ['a', 'b', 'c', 'd', 'e', 'f']
>>> it(lst)pyiter.windowed(3, 2, True).to_list()
[['a', 'b', 'c'], ['c', 'd', 'e'], ['e', 'f']]
2680 def chunked(self, size: int) -> Stream[List[T]]: 2681 """ 2682 Returns a Stream of all possible chunks of size [size] from the given Stream. 2683 2684 Example 1: 2685 >>> lst = ['a', 'b', 'c', 'd', 'e'] 2686 >>> it(lst).chunked(3).to_list() 2687 [['a', 'b', 'c'], ['d', 'e']] 2688 2689 2690 Example 2: 2691 >>> lst = ['a', 'b', 'c', 'd', 'e', 'f'] 2692 >>> it(lst).chunked(3).to_list() 2693 [['a', 'b', 'c'], ['d', 'e', 'f']] 2694 """ 2695 return self.windowed(size, size, True)
Returns a Stream of all possible chunks of size [size] from the given Stream.
Example 1:
>>> lst = ['a', 'b', 'c', 'd', 'e']
>>> it(lst).chunked(3).to_list()
[['a', 'b', 'c'], ['d', 'e']]
Example 2:
>>> lst = ['a', 'b', 'c', 'd', 'e', 'f']
>>> it(lst).chunked(3).to_list()
[['a', 'b', 'c'], ['d', 'e', 'f']]
2697 def repeat(self, n: int) -> Stream[T]: 2698 """ 2699 Returns a Stream containing this sequence repeated n times. 2700 2701 Example 1: 2702 >>> lst = ['a', 'b'] 2703 >>> it(lst).repeat(3).to_list() 2704 ['a', 'b', 'a', 'b', 'a', 'b'] 2705 """ 2706 from .concat import ConcatTransform 2707 2708 return it(ConcatTransform([self] * n))
Returns a Stream containing this sequence repeated n times.
Example 1:
>>> lst = ['a', 'b']
>>> it(lst).repeat(3).to_list()
['a', 'b', 'a', 'b', 'a', 'b']
2710 def concat(self, *other: Iterable[T]) -> Stream[T]: 2711 """ 2712 Returns a Stream of all elements of the given Stream, followed by all elements of the given Stream. 2713 2714 Example 1: 2715 >>> lst1 = ['a', 'b', 'c'] 2716 >>> lst2 = [1, 2, 3] 2717 >>> it(lst1).concat(lst2).to_list() 2718 ['a', 'b', 'c', 1, 2, 3] 2719 2720 Example 2: 2721 >>> lst1 = ['a', 'b', 'c'] 2722 >>> lst2 = [1, 2, 3] 2723 >>> lst3 = [4, 5, 6] 2724 >>> it(lst1).concat(lst2, lst3).to_list() 2725 ['a', 'b', 'c', 1, 2, 3, 4, 5, 6] 2726 """ 2727 from .concat import ConcatTransform 2728 2729 return it(ConcatTransform([self, *other]))
Returns a Stream of all elements of the given Stream, followed by all elements of the given Stream.
Example 1:
>>> lst1 = ['a', 'b', 'c']
>>> lst2 = [1, 2, 3]
>>> it(lst1)pyiter.concat(lst2).to_list()
['a', 'b', 'c', 1, 2, 3]
Example 2:
>>> lst1 = ['a', 'b', 'c']
>>> lst2 = [1, 2, 3]
>>> lst3 = [4, 5, 6]
>>> it(lst1)pyiter.concat(lst2, lst3).to_list()
['a', 'b', 'c', 1, 2, 3, 4, 5, 6]
2731 def intersect(self, *other: Iterable[T]) -> Stream[T]: 2732 """ 2733 Returns a set containing all elements that are contained by both this collection and the specified collection. 2734 2735 The returned set preserves the element iteration order of the original collection. 2736 2737 To get a set containing all elements that are contained at least in one of these collections use union. 2738 2739 Example 1: 2740 >>> lst1 = ['a', 'b', 'c'] 2741 >>> lst2 = ['a2', 'b2', 'c'] 2742 >>> it(lst1).intersect(lst2).to_list() 2743 ['c'] 2744 2745 Example 2: 2746 >>> lst1 = ['a', 'b', 'c'] 2747 >>> lst2 = ['a2', 'b', 'c'] 2748 >>> lst3 = ['a3', 'b', 'c3'] 2749 >>> it(lst1).intersect(lst2, lst3).to_list() 2750 ['b'] 2751 2752 2753 Example 1: 2754 >>> lst1 = ['a', 'a', 'c'] 2755 >>> lst2 = ['a2', 'b2', 'a'] 2756 >>> it(lst1).intersect(lst2).to_list() 2757 ['a'] 2758 """ 2759 from .intersection import IntersectionTransform 2760 2761 return it(IntersectionTransform([self, *other]))
Returns a set containing all elements that are contained by both this collection and the specified collection.
The returned set preserves the element iteration order of the original collection.
To get a set containing all elements that are contained at least in one of these collections use union.
Example 1:
>>> lst1 = ['a', 'b', 'c']
>>> lst2 = ['a2', 'b2', 'c']
>>> it(lst1).intersect(lst2).to_list()
['c']
Example 2:
>>> lst1 = ['a', 'b', 'c']
>>> lst2 = ['a2', 'b', 'c']
>>> lst3 = ['a3', 'b', 'c3']
>>> it(lst1).intersect(lst2, lst3).to_list()
['b']
Example 1:
>>> lst1 = ['a', 'a', 'c']
>>> lst2 = ['a2', 'b2', 'a']
>>> it(lst1).intersect(lst2).to_list()
['a']
2763 def union(self, *other: Stream[T]) -> Stream[T]: 2764 """ 2765 Returns a set containing all distinct elements from both collections. 2766 2767 The returned set preserves the element iteration order of the original collection. Those elements of the other collection that are unique are iterated in the end in the order of the other collection. 2768 2769 To get a set containing all elements that are contained in both collections use intersect. 2770 2771 Example 1: 2772 >>> lst1 = ['a', 'b', 'c'] 2773 >>> lst2 = ['a2', 'b2', 'c'] 2774 >>> it(lst1).union(lst2).to_list() 2775 ['a', 'b', 'c', 'a2', 'b2'] 2776 2777 Example 2: 2778 >>> lst1 = ['a', 'b', 'c'] 2779 >>> lst2 = ['a2', 'b', 'c'] 2780 >>> lst3 = ['a3', 'b', 'c3'] 2781 >>> it(lst1).union(lst2, lst3).to_list() 2782 ['a', 'b', 'c', 'a2', 'a3', 'c3'] 2783 2784 2785 Example 1: 2786 >>> lst1 = ['a', 'a', 'c'] 2787 >>> lst2 = ['a2', 'b2', 'a'] 2788 >>> it(lst1).union(lst2).to_list() 2789 ['a', 'c', 'a2', 'b2'] 2790 """ 2791 return self.concat(*other).distinct()
Returns a set containing all distinct elements from both collections.
The returned set preserves the element iteration order of the original collection. Those elements of the other collection that are unique are iterated in the end in the order of the other collection.
To get a set containing all elements that are contained in both collections use intersect.
Example 1:
>>> lst1 = ['a', 'b', 'c']
>>> lst2 = ['a2', 'b2', 'c']
>>> it(lst1).union(lst2).to_list()
['a', 'b', 'c', 'a2', 'b2']
Example 2:
>>> lst1 = ['a', 'b', 'c']
>>> lst2 = ['a2', 'b', 'c']
>>> lst3 = ['a3', 'b', 'c3']
>>> it(lst1).union(lst2, lst3).to_list()
['a', 'b', 'c', 'a2', 'a3', 'c3']
Example 1:
>>> lst1 = ['a', 'a', 'c']
>>> lst2 = ['a2', 'b2', 'a']
>>> it(lst1).union(lst2).to_list()
['a', 'c', 'a2', 'b2']
2793 def join(self: Stream[str], separator: str = " ") -> str: 2794 """ 2795 Joins the elements of the given Stream into a string. 2796 2797 Example 1: 2798 >>> lst = ['a', 'b', 'c'] 2799 >>> it(lst).join(', ') 2800 'a, b, c' 2801 """ 2802 return separator.join(self)
Joins the elements of the given Stream into a string.
Example 1:
>>> lst = ['a', 'b', 'c']
>>> it(lst).join(', ')
'a, b, c'
2812 def progress( 2813 self, 2814 progress_func: Union[ 2815 Callable[[Stream[T]], Iterable[T]], 2816 Literal["tqdm"], 2817 Literal["tqdm_rich"], 2818 None, 2819 ] = None, 2820 ) -> Stream[T]: 2821 """ 2822 Returns a Stream that enable a progress bar for the given Stream. 2823 2824 Example 1: 2825 >>> from tqdm import tqdm 2826 >>> from time import sleep 2827 >>> it(range(10)).progress(lambda x: tqdm(x, total=len(x))).parallel_map(lambda x: sleep(0.), max_workers=5).to_list() and None 2828 >>> for _ in it(list(range(10))).progress(lambda x: tqdm(x, total=len(x))).to_list(): pass 2829 """ 2830 if progress_func is not None and callable(progress_func): 2831 return it(progress_func(self)) 2832 2833 def import_tqdm(): 2834 if progress_func == "tqdm_rich": 2835 import warnings 2836 from tqdm.rich import tqdm 2837 from tqdm import TqdmExperimentalWarning 2838 2839 warnings.filterwarnings("ignore", category=TqdmExperimentalWarning) 2840 else: 2841 from tqdm import tqdm 2842 return tqdm 2843 2844 try: 2845 tqdm = import_tqdm() 2846 except ImportError: 2847 from pip import main as pip # type: ignore 2848 2849 pip(["install", "tqdm"]) 2850 tqdm = import_tqdm() 2851 2852 return it(tqdm(self, total=len(self)))
Returns a Stream that enable a progress bar for the given Stream.
Example 1:
>>> from tqdm import tqdm
>>> from time import sleep
>>> it(range(10)).progress(lambda x: tqdm(x, total=len(x))).parallel_map(lambda x: sleep(0.), max_workers=5).to_list() and None
>>> for _ in it(list(range(10))).progress(lambda x: tqdm(x, total=len(x))).to_list(): pass
2854 def typing_as(self, typ: Type[U]) -> Stream[U]: 2855 """ 2856 Cast the element as specific Type to gain code completion base on type annotations. 2857 """ 2858 el = self.first_not_none_of_or_none() 2859 if el is None or isinstance(el, typ) or not isinstance(el, dict): 2860 return self # type: ignore 2861 2862 class AttrDict(Dict[str, Any]): 2863 def __init__(self, value: Dict[str, Any]) -> None: 2864 super().__init__(**value) 2865 setattr(self, "__dict__", value) 2866 self.__getattr__ = value.__getitem__ 2867 self.__setattr__ = value.__setattr__ # type: ignore 2868 2869 return self.map(AttrDict) # type: ignore # use https://github.com/cdgriffith/Box ?
Cast the element as specific Type to gain code completion base on type annotations.
2871 def to_set(self) -> Set[T]: 2872 """ 2873 Returns a set containing all elements of this Stream. 2874 2875 Example 1: 2876 >>> it(['a', 'b', 'c', 'c']).to_set() == {'a', 'b', 'c'} 2877 True 2878 """ 2879 return set(self)
Returns a set containing all elements of this Stream.
Example 1:
>>> it(['a', 'b', 'c', 'c']).to_set() == {'a', 'b', 'c'}
True
2889 def to_dict(self, transform: Optional[Callable[..., Tuple[K, V]]] = None) -> Dict[K, V]: 2890 """ 2891 Returns a [Dict] containing key-value Tuple provided by [transform] function 2892 applied to elements of the given Stream. 2893 2894 Example 1: 2895 >>> lst = ['1', '2', '3'] 2896 >>> it(lst).to_dict(lambda x: (int(x), x)) 2897 {1: '1', 2: '2', 3: '3'} 2898 2899 Example 2: 2900 >>> lst = [(1, '1'), (2, '2'), (3, '3')] 2901 >>> it(lst).to_dict() 2902 {1: '1', 2: '2', 3: '3'} 2903 """ 2904 return self.associate(transform or (lambda x: x)) # type: ignore
Returns a [Dict] containing key-value Tuple provided by [transform] function applied to elements of the given Stream.
Example 1:
>>> lst = ['1', '2', '3']
>>> it(lst).to_dict(lambda x: (int(x), x))
{1: '1', 2: '2', 3: '3'}
Example 2:
>>> lst = [(1, '1'), (2, '2'), (3, '3')]
>>> it(lst).to_dict()
{1: '1', 2: '2', 3: '3'}
2906 def to_list(self) -> List[T]: 2907 """ 2908 Returns a list with elements of the given Stream. 2909 2910 Example 1: 2911 >>> it(['b', 'c', 'a']).to_list() 2912 ['b', 'c', 'a'] 2913 """ 2914 if self.__transform__.cache is not None: 2915 return self.__transform__.cache.copy() 2916 return [s for s in self]
Returns a list with elements of the given Stream.
Example 1:
>>> it(['b', 'c', 'a']).to_list()
['b', 'c', 'a']
2918 async def to_list_async(self: Iterable[Awaitable[T]]) -> List[T]: 2919 """ 2920 Returns a list with elements of the given Stream. 2921 2922 Example 1: 2923 >>> it(['b', 'c', 'a']).to_list() 2924 ['b', 'c', 'a'] 2925 """ 2926 from asyncio import gather 2927 2928 return await gather(*self) # type: ignore
Returns a list with elements of the given Stream.
Example 1:
>>> it(['b', 'c', 'a']).to_list()
['b', 'c', 'a']
2930 def let(self, block: Callable[[Stream[T]], U]) -> U: 2931 """ 2932 Calls the specified function [block] with `self` value as its argument and returns its result. 2933 2934 Example 1: 2935 >>> it(['a', 'b', 'c']).let(lambda x: x.map(lambda y: y + '!')).to_list() 2936 ['a!', 'b!', 'c!'] 2937 """ 2938 return block(self)
Calls the specified function [block] with self value as its argument and returns its result.
Example 1:
>>> it(['a', 'b', 'c']).let(lambda x: x.map(lambda y: y + '!')).to_list()
['a!', 'b!', 'c!']
2940 def also(self, block: Callable[[Stream[T]], Any]) -> Stream[T]: 2941 """ 2942 Calls the specified function [block] with `self` value as its argument and returns `self` value. 2943 2944 Example 1: 2945 >>> it(['a', 'b', 'c']).also(lambda x: x.map(lambda y: y + '!')).to_list() 2946 ['a', 'b', 'c'] 2947 """ 2948 block(self) 2949 return self
Calls the specified function [block] with self value as its argument and returns self value.
Example 1:
>>> it(['a', 'b', 'c']).also(lambda x: x.map(lambda y: y + '!')).to_list()
['a', 'b', 'c']
2951 @property 2952 def size(self) -> int: 2953 """ 2954 Returns the size of the given Stream. 2955 """ 2956 return len(self.data)
Returns the size of the given Stream.
2958 def is_empty(self) -> bool: 2959 """ 2960 Returns True if the Stream is empty, False otherwise. 2961 2962 Example 1: 2963 >>> it(['a', 'b', 'c']).is_empty() 2964 False 2965 2966 Example 2: 2967 >>> it([None]).is_empty() 2968 False 2969 2970 Example 3: 2971 >>> it([]).is_empty() 2972 True 2973 """ 2974 return id(self.first_or_default(self)) == id(self)
Returns True if the Stream is empty, False otherwise.
Example 1:
>>> it(['a', 'b', 'c']).is_empty()
False
Example 2:
>>> it([None]).is_empty()
False
Example 3:
>>> it([]).is_empty()
True
3081class StreamProducer: 3082 @overload 3083 def __call__(self, elements: List[T]) -> Stream[T]: ... 3084 @overload 3085 def __call__(self, elements: Iterable[T]) -> Stream[T]: ... 3086 @overload 3087 def __call__(self, *elements: T) -> Stream[T]: ... 3088 def __call__(self, *iterable: Union[Iterable[T], List[T], T]) -> Stream[T]: # type: ignore 3089 if len(iterable) == 1: 3090 iter = iterable[0] 3091 if isinstance(iter, Stream): 3092 return iter # type: ignore 3093 if isinstance(iter, Iterable) and not isinstance(iter, str): 3094 return Stream(iter) # type: ignore 3095 return Stream(iterable) # type: ignore 3096 3097 def json(self, filepath: str, **kwargs: Dict[str, Any]) -> Stream[Any]: 3098 """ 3099 Reads and parses the input of a json file. 3100 """ 3101 import json 3102 3103 with open(filepath, "r") as f: 3104 data = json.load(f, **kwargs) # type: ignore 3105 return self(data) 3106 3107 def csv(self, filepath: str) -> Stream[List[str]] | Stream[Dict[str, str]]: 3108 """ 3109 Reads and parses the input of a csv file. 3110 """ 3111 return self.read_csv(filepath) 3112 3113 def read_csv( 3114 self, filepath: str, header: Optional[int] = 0 3115 ) -> Stream[List[str]] | Stream[Dict[str, str]]: 3116 """ 3117 Reads and parses the input of a csv file. 3118 3119 Example 1: 3120 >>> it.read_csv('tests/data/a.csv').to_list() 3121 [{'a': 'a1', 'b': '1'}, {'a': 'a2', 'b': '2'}] 3122 """ 3123 import csv 3124 3125 it = self 3126 with open(filepath) as f: 3127 reader = csv.reader(f) 3128 iter = it(*reader) 3129 if header is None or header < 0: 3130 return iter 3131 3132 headers = iter.element_at_or_none(header) 3133 if headers is not None: 3134 if header == 0: 3135 iter = iter.skip(1) 3136 else: 3137 iter = iter.filter(lambda _, i: i != header) 3138 3139 return iter.map( 3140 lambda row: it(row).associate_by( 3141 lambda _, ordinal: ( 3142 headers[ordinal] if ordinal < len(headers) else f"undefined_{ordinal}" 3143 ) 3144 ) 3145 ) 3146 return iter 3147 3148 def __repr__(self) -> str: 3149 return __package__ or self.__class__.__name__
3097 def json(self, filepath: str, **kwargs: Dict[str, Any]) -> Stream[Any]: 3098 """ 3099 Reads and parses the input of a json file. 3100 """ 3101 import json 3102 3103 with open(filepath, "r") as f: 3104 data = json.load(f, **kwargs) # type: ignore 3105 return self(data)
Reads and parses the input of a json file.
3107 def csv(self, filepath: str) -> Stream[List[str]] | Stream[Dict[str, str]]: 3108 """ 3109 Reads and parses the input of a csv file. 3110 """ 3111 return self.read_csv(filepath)
Reads and parses the input of a csv file.
3113 def read_csv( 3114 self, filepath: str, header: Optional[int] = 0 3115 ) -> Stream[List[str]] | Stream[Dict[str, str]]: 3116 """ 3117 Reads and parses the input of a csv file. 3118 3119 Example 1: 3120 >>> it.read_csv('tests/data/a.csv').to_list() 3121 [{'a': 'a1', 'b': '1'}, {'a': 'a2', 'b': '2'}] 3122 """ 3123 import csv 3124 3125 it = self 3126 with open(filepath) as f: 3127 reader = csv.reader(f) 3128 iter = it(*reader) 3129 if header is None or header < 0: 3130 return iter 3131 3132 headers = iter.element_at_or_none(header) 3133 if headers is not None: 3134 if header == 0: 3135 iter = iter.skip(1) 3136 else: 3137 iter = iter.filter(lambda _, i: i != header) 3138 3139 return iter.map( 3140 lambda row: it(row).associate_by( 3141 lambda _, ordinal: ( 3142 headers[ordinal] if ordinal < len(headers) else f"undefined_{ordinal}" 3143 ) 3144 ) 3145 ) 3146 return iter
Reads and parses the input of a csv file.
Example 1:
>>> it.read_csv('tests/data/a.csv').to_list()
[{'a': 'a1', 'b': '1'}, {'a': 'a2', 'b': '2'}]
3064def is_debugging() -> bool: 3065 from inspect import currentframe 3066 from traceback import walk_stack 3067 3068 return ( 3069 it(walk_stack(currentframe())) 3070 .take(20) 3071 .map(lambda s: s[0]) 3072 .any( 3073 lambda s: ( 3074 s.f_code.co_name == "get_contents_debug_adapter_protocol" 3075 and "pydevd_resolver.py" in s.f_code.co_filename 3076 ) 3077 ) 3078 )
Deprecated. Use pyiter.it instead.
Example 1:
>>> seq('hello', 'world').map(lambda x: x.upper()).to_list()
['HELLO', 'WORLD']
Example 2:
>>> seq(['hello', 'world']).map(lambda x: x.upper()).to_list()
['HELLO', 'WORLD']
Example 3:
>>> seq(range(10)).map(lambda x: x*x).to_list()
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Deprecated. Use pyiter.it instead.
Example 1:
>>> sequence('hello', 'world').map(lambda x: x.upper()).to_list()
['HELLO', 'WORLD']
Example 2:
>>> sequence(['hello', 'world']).map(lambda x: x.upper()).to_list()
['HELLO', 'WORLD']
Example 3:
>>> sequence(range(10)).map(lambda x: x*x).to_list()
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]