dc-cmnutils 0.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,757 @@
1
+ from typing import (
2
+ Any, List, Dict, Set, Tuple, Optional, Union, Iterable, Callable,
3
+ Iterator, DefaultDict, Counter as CounterType
4
+ )
5
+ from collections import defaultdict, Counter
6
+ import itertools
7
+ import operator
8
+ from dc.cmnlib.collection.collection import CollectionHelper
9
+
10
+ class CollectionUtils(CollectionHelper):
11
+ """集合操作工具类"""
12
+
13
+ @staticmethod
14
+ def flatten(nested_list: Iterable) -> List:
15
+ """
16
+ 扁平化嵌套列表
17
+
18
+ Args:
19
+ nested_list: 嵌套列表
20
+
21
+ Returns:
22
+ 扁平化后的列表
23
+
24
+ Example:
25
+ >>> CollectionUtils.flatten([[1, 2], [3, [4, 5]]])
26
+ [1, 2, 3, 4, 5]
27
+ """
28
+ result = []
29
+ for item in nested_list:
30
+ if isinstance(item, (list, tuple, set)):
31
+ result.extend(CollectionUtils.flatten(item))
32
+ else:
33
+ result.append(item)
34
+ return result
35
+
36
+ @staticmethod
37
+ def chunk(iterable: Iterable, size: int) -> Iterator[List]:
38
+ """
39
+ 将可迭代对象分块
40
+
41
+ Args:
42
+ iterable: 可迭代对象
43
+ size: 每块大小
44
+
45
+ Returns:
46
+ 分块后的迭代器
47
+
48
+ Example:
49
+ >>> list(CollectionUtils.chunk([1, 2, 3, 4, 5], 2))
50
+ [[1, 2], [3, 4], [5]]
51
+ """
52
+ it = iter(iterable)
53
+ while True:
54
+ chunk = list(itertools.islice(it, size))
55
+ if not chunk:
56
+ break
57
+ yield chunk
58
+
59
+ @staticmethod
60
+ def distinct(iterable: Iterable) -> List:
61
+ """
62
+ 去重并保持顺序
63
+
64
+ Args:
65
+ iterable: 可迭代对象
66
+
67
+ Returns:
68
+ 去重后的列表
69
+
70
+ Example:
71
+ >>> CollectionUtils.distinct([1, 2, 2, 3, 1])
72
+ [1, 2, 3]
73
+ """
74
+ seen = set()
75
+ result = []
76
+ for item in iterable:
77
+ if item not in seen:
78
+ seen.add(item)
79
+ result.append(item)
80
+ return result
81
+
82
+ @staticmethod
83
+ def group_by(iterable: Iterable, key_func: Callable) -> DefaultDict[Any, List]:
84
+ """
85
+ 根据指定键函数分组
86
+
87
+ Args:
88
+ iterable: 可迭代对象
89
+ key_func: 键函数
90
+
91
+ Returns:
92
+ 分组后的字典
93
+
94
+ Example:
95
+ >>> CollectionUtils.group_by([1, 2, 3, 4], lambda x: x % 2)
96
+ defaultdict(<class 'list'>, {1: [1, 3], 0: [2, 4]})
97
+ """
98
+ grouped = defaultdict(list)
99
+ for item in iterable:
100
+ key = key_func(item)
101
+ grouped[key].append(item)
102
+ return grouped
103
+
104
+ @staticmethod
105
+ def sort_by(iterable: Iterable, key_func: Callable, reverse: bool = False) -> List:
106
+ """
107
+ 根据指定键函数排序
108
+
109
+ Args:
110
+ iterable: 可迭代对象
111
+ key_func: 键函数
112
+ reverse: 是否降序
113
+
114
+ Returns:
115
+ 排序后的列表
116
+
117
+ Example:
118
+ >>> CollectionUtils.sort_by([{'a': 2}, {'a': 1}], lambda x: x['a'])
119
+ [{'a': 1}, {'a': 2}]
120
+ """
121
+ return sorted(iterable, key=key_func, reverse=reverse)
122
+
123
+ @staticmethod
124
+ def filter_by(iterable: Iterable, predicate: Callable) -> List:
125
+ """
126
+ 根据谓词函数过滤
127
+
128
+ Args:
129
+ iterable: 可迭代对象
130
+ predicate: 谓词函数
131
+
132
+ Returns:
133
+ 过滤后的列表
134
+
135
+ Example:
136
+ >>> CollectionUtils.filter_by([1, 2, 3, 4], lambda x: x % 2 == 0)
137
+ [2, 4]
138
+ """
139
+ return [item for item in iterable if predicate(item)]
140
+
141
+ @staticmethod
142
+ def map_to(iterable: Iterable, func: Callable) -> List:
143
+ """
144
+ 映射每个元素
145
+
146
+ Args:
147
+ iterable: 可迭代对象
148
+ func: 映射函数
149
+
150
+ Returns:
151
+ 映射后的列表
152
+
153
+ Example:
154
+ >>> CollectionUtils.map_to([1, 2, 3], lambda x: x * 2)
155
+ [2, 4, 6]
156
+ """
157
+ return [func(item) for item in iterable]
158
+
159
+ @staticmethod
160
+ def find(iterable: Iterable, predicate: Callable) -> Optional[Any]:
161
+ """
162
+ 查找第一个满足条件的元素
163
+ Args:
164
+ iterable: 可迭代对象
165
+ predicate: 谓词函数
166
+ Returns:
167
+ 第一个满足条件的元素,如果没有则返回None
168
+ Example:
169
+ >>> CollectionUtils.find([1, 2, 3, 4], lambda x: x > 2)
170
+ 3
171
+ """
172
+ for item in iterable:
173
+ if predicate(item):
174
+ return item
175
+ return None
176
+
177
+ @staticmethod
178
+ def find_index(iterable: Iterable, predicate: Callable) -> int:
179
+ """
180
+ 查找第一个满足条件的元素的索引
181
+
182
+ Args:
183
+ iterable: 可迭代对象
184
+ predicate: 谓词函数
185
+
186
+ Returns:
187
+ 第一个满足条件的元素的索引,如果没有则返回-1
188
+
189
+ Example:
190
+ >>> CollectionUtils.find_index([1, 2, 3, 4], lambda x: x > 2)
191
+ 2
192
+ """
193
+ for i, item in enumerate(iterable):
194
+ if predicate(item):
195
+ return i
196
+ return -1
197
+
198
+ @staticmethod
199
+ def all_match(iterable: Iterable, predicate: Callable) -> bool:
200
+ """
201
+ 检查所有元素是否都满足条件
202
+
203
+ Args:
204
+ iterable: 可迭代对象
205
+ predicate: 谓词函数
206
+
207
+ Returns:
208
+ 是否所有元素都满足条件
209
+
210
+ Example:
211
+ >>> CollectionUtils.all_match([2, 4, 6], lambda x: x % 2 == 0)
212
+ True
213
+ """
214
+ return all(predicate(item) for item in iterable)
215
+
216
+ @staticmethod
217
+ def any_match(iterable: Iterable, predicate: Callable) -> bool:
218
+ """
219
+ 检查是否有任意元素满足条件
220
+
221
+ Args:
222
+ iterable: 可迭代对象
223
+ predicate: 谓词函数
224
+
225
+ Returns:
226
+ 是否有任意元素满足条件
227
+
228
+ Example:
229
+ >>> CollectionUtils.any_match([1, 3, 5], lambda x: x % 2 == 0)
230
+ False
231
+ """
232
+ return any(predicate(item) for item in iterable)
233
+
234
+ @staticmethod
235
+ def none_match(iterable: Iterable, predicate: Callable) -> bool:
236
+ """
237
+ 检查是否没有元素满足条件
238
+
239
+ Args:
240
+ iterable: 可迭代对象
241
+ predicate: 谓词函数
242
+
243
+ Returns:
244
+ 是否没有元素满足条件
245
+
246
+ Example:
247
+ >>> CollectionUtils.none_match([1, 3, 5], lambda x: x % 2 == 0)
248
+ True
249
+ """
250
+ return not CollectionUtils.any_match(iterable, predicate)
251
+
252
+ @staticmethod
253
+ def count_matching(iterable: Iterable, predicate: Callable) -> int:
254
+ """
255
+ 统计满足条件的元素数量
256
+
257
+ Args:
258
+ iterable: 可迭代对象
259
+ predicate: 谓词函数
260
+
261
+ Returns:
262
+ 满足条件的元素数量
263
+
264
+ Example:
265
+ >>> CollectionUtils.count_matching([1, 2, 3, 4], lambda x: x % 2 == 0)
266
+ 2
267
+ """
268
+ return sum(1 for item in iterable if predicate(item))
269
+
270
+ @staticmethod
271
+ def zip_with_index(iterable: Iterable) -> Iterator[Tuple[int, Any]]:
272
+ """
273
+ 将元素与索引压缩
274
+
275
+ Args:
276
+ iterable: 可迭代对象
277
+
278
+ Returns:
279
+ (索引, 元素)的迭代器
280
+
281
+ Example:
282
+ >>> list(CollectionUtils.zip_with_index(['a', 'b', 'c']))
283
+ [(0, 'a'), (1, 'b'), (2, 'c')]
284
+ """
285
+ return enumerate(iterable)
286
+
287
+ @staticmethod
288
+ def partition(iterable: Iterable, predicate: Callable) -> Tuple[List, List]:
289
+ """
290
+ 根据谓词函数分区
291
+
292
+ Args:
293
+ iterable: 可迭代对象
294
+ predicate: 谓词函数
295
+
296
+ Returns:
297
+ (满足条件的元素列表, 不满足条件的元素列表)
298
+
299
+ Example:
300
+ >>> CollectionUtils.partition([1, 2, 3, 4], lambda x: x % 2 == 0)
301
+ ([2, 4], [1, 3])
302
+ """
303
+ true_list = []
304
+ false_list = []
305
+ for item in iterable:
306
+ if predicate(item):
307
+ true_list.append(item)
308
+ else:
309
+ false_list.append(item)
310
+ return true_list, false_list
311
+
312
+ @staticmethod
313
+ def max_by(iterable: Iterable, key_func: Callable) -> Optional[Any]:
314
+ """
315
+ 根据键函数查找最大元素
316
+
317
+ Args:
318
+ iterable: 可迭代对象
319
+ key_func: 键函数
320
+
321
+ Returns:
322
+ 最大元素,如果可迭代对象为空则返回None
323
+
324
+ Example:
325
+ >>> CollectionUtils.max_by([{'a': 1}, {'a': 3}, {'a': 2}], lambda x: x['a'])
326
+ {'a': 3}
327
+ """
328
+ if not iterable:
329
+ return None
330
+ return max(iterable, key=key_func)
331
+
332
+ @staticmethod
333
+ def min_by(iterable: Iterable, key_func: Callable) -> Optional[Any]:
334
+ """
335
+ 根据键函数查找最小元素
336
+
337
+ Args:
338
+ iterable: 可迭代对象
339
+ key_func: 键函数
340
+
341
+ Returns:
342
+ 最小元素,如果可迭代对象为空则返回None
343
+
344
+ Example:
345
+ >>> CollectionUtils.min_by([{'a': 1}, {'a': 3}, {'a': 2}], lambda x: x['a'])
346
+ {'a': 1}
347
+ """
348
+ if not iterable:
349
+ return None
350
+ return min(iterable, key=key_func)
351
+
352
+ @staticmethod
353
+ def sum_by(iterable: Iterable, key_func: Callable) -> Any:
354
+ """
355
+ 根据键函数求和
356
+
357
+ Args:
358
+ iterable: 可迭代对象
359
+ key_func: 键函数
360
+
361
+ Returns:
362
+ 求和结果
363
+
364
+ Example:
365
+ >>> CollectionUtils.sum_by([{'a': 1}, {'a': 2}, {'a': 3}], lambda x: x['a'])
366
+ 6
367
+ """
368
+ return sum(key_func(item) for item in iterable)
369
+
370
+ @staticmethod
371
+ def average_by(iterable: Iterable, key_func: Callable) -> float:
372
+ """
373
+ 根据键函数求平均值
374
+
375
+ Args:
376
+ iterable: 可迭代对象
377
+ key_func: 键函数
378
+
379
+ Returns:
380
+ 平均值
381
+
382
+ Example:
383
+ >>> CollectionUtils.average_by([{'a': 1}, {'a': 2}, {'a': 3}], lambda x: x['a'])
384
+ 2.0
385
+ """
386
+ items = list(iterable)
387
+ if not items:
388
+ return 0.0
389
+ return CollectionUtils.sum_by(items, key_func) / len(items)
390
+
391
+ @staticmethod
392
+ def frequency(iterable: Iterable) -> Dict[Any, int]:
393
+ """
394
+ 计算元素频率
395
+
396
+ Args:
397
+ iterable: 可迭代对象
398
+
399
+ Returns:
400
+ 元素频率字典
401
+
402
+ Example:
403
+ >>> CollectionUtils.frequency(['a', 'b', 'a', 'c', 'b'])
404
+ {'a': 2, 'b': 2, 'c': 1}
405
+ """
406
+ return dict(Counter(iterable))
407
+
408
+ @staticmethod
409
+ def reverse(iterable: Iterable) -> List:
410
+ """
411
+ 反转可迭代对象
412
+
413
+ Args:
414
+ iterable: 可迭代对象
415
+
416
+ Returns:
417
+ 反转后的列表
418
+
419
+ Example:
420
+ >>> CollectionUtils.reverse([1, 2, 3])
421
+ [3, 2, 1]
422
+ """
423
+ return list(reversed(iterable))
424
+
425
+ @staticmethod
426
+ def join(iterable: Iterable, separator: str = ', ') -> str:
427
+ """
428
+ 将元素连接成字符串
429
+
430
+ Args:
431
+ iterable: 可迭代对象
432
+ separator: 分隔符
433
+
434
+ Returns:
435
+ 连接后的字符串
436
+
437
+ Example:
438
+ >>> CollectionUtils.join([1, 2, 3], '-')
439
+ '1-2-3'
440
+ """
441
+ return separator.join(str(item) for item in iterable)
442
+
443
+ @staticmethod
444
+ def take_while(iterable: Iterable, predicate: Callable) -> List:
445
+ """
446
+ 获取满足条件的连续元素直到条件不满足
447
+
448
+ Args:
449
+ iterable: 可迭代对象
450
+ predicate: 谓词函数
451
+
452
+ Returns:
453
+ 满足条件的连续元素列表
454
+
455
+ Example:
456
+ >>> CollectionUtils.take_while([1, 2, 3, 4, 1], lambda x: x < 4)
457
+ [1, 2, 3]
458
+ """
459
+ result = []
460
+ for item in iterable:
461
+ if predicate(item):
462
+ result.append(item)
463
+ else:
464
+ break
465
+ return result
466
+
467
+ @staticmethod
468
+ def drop_while(iterable: Iterable, predicate: Callable) -> List:
469
+ """
470
+ 丢弃满足条件的连续元素直到条件不满足
471
+
472
+ Args:
473
+ iterable: 可迭代对象
474
+ predicate: 谓词函数
475
+
476
+ Returns:
477
+ 剩余元素列表
478
+
479
+ Example:
480
+ >>> CollectionUtils.drop_while([1, 2, 3, 4, 1], lambda x: x < 4)
481
+ [4, 1]
482
+ """
483
+ result = []
484
+ found = False
485
+ for item in iterable:
486
+ if not found and not predicate(item):
487
+ found = True
488
+ if found:
489
+ result.append(item)
490
+ return result
491
+
492
+ @staticmethod
493
+ def sliding_window(iterable: Iterable, size: int) -> Iterator[List]:
494
+ """
495
+ 生成滑动窗口
496
+
497
+ Args:
498
+ iterable: 可迭代对象
499
+ size: 窗口大小
500
+
501
+ Returns:
502
+ 滑动窗口迭代器
503
+
504
+ Example:
505
+ >>> list(CollectionUtils.sliding_window([1, 2, 3, 4], 2))
506
+ [[1, 2], [2, 3], [3, 4]]
507
+ """
508
+ it = iter(iterable)
509
+ window = list(itertools.islice(it, size))
510
+ if len(window) == size:
511
+ yield window.copy()
512
+
513
+ for item in it:
514
+ window.pop(0)
515
+ window.append(item)
516
+ yield window.copy()
517
+
518
+ @staticmethod
519
+ def cartesian_product(*iterables: Iterable) -> Iterator[Tuple]:
520
+ """
521
+ 计算多个可迭代对象的笛卡尔积
522
+
523
+ Args:
524
+ *iterables: 多个可迭代对象
525
+
526
+ Returns:
527
+ 笛卡尔积迭代器
528
+
529
+ Example:
530
+ >>> list(CollectionUtils.cartesian_product([1, 2], ['a', 'b']))
531
+ [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
532
+ """
533
+ return itertools.product(*iterables)
534
+
535
+ @staticmethod
536
+ def permutations(iterable: Iterable, r: Optional[int] = None) -> Iterator[Tuple]:
537
+ """
538
+ 生成排列
539
+
540
+ Args:
541
+ iterable: 可迭代对象
542
+ r: 排列长度,默认为可迭代对象长度
543
+
544
+ Returns:
545
+ 排列迭代器
546
+
547
+ Example:
548
+ >>> list(CollectionUtils.permutations([1, 2, 3], 2))
549
+ [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
550
+ """
551
+ return itertools.permutations(iterable, r)
552
+
553
+ @staticmethod
554
+ def combinations(iterable: Iterable, r: int) -> Iterator[Tuple]:
555
+ """
556
+ 生成组合
557
+
558
+ Args:
559
+ iterable: 可迭代对象
560
+ r: 组合长度
561
+
562
+ Returns:
563
+ 组合迭代器
564
+
565
+ Example:
566
+ >>> list(CollectionUtils.combinations([1, 2, 3], 2))
567
+ [(1, 2), (1, 3), (2, 3)]
568
+ """
569
+ return itertools.combinations(iterable, r)
570
+
571
+ @staticmethod
572
+ def transpose(matrix: List[List]) -> List[List]:
573
+ """
574
+ 转置矩阵(二维列表)
575
+
576
+ Args:
577
+ matrix: 二维列表
578
+
579
+ Returns:
580
+ 转置后的二维列表
581
+
582
+ Example:
583
+ >>> CollectionUtils.transpose([[1, 2, 3], [4, 5, 6]])
584
+ [[1, 4], [2, 5], [3, 6]]
585
+ """
586
+ if not matrix:
587
+ return []
588
+ return [list(column) for column in zip(*matrix)]
589
+
590
+ @staticmethod
591
+ def deep_flatten(nested_list: Iterable) -> List:
592
+ """
593
+ 深度扁平化嵌套列表(与flatten方法相同,提供别名)
594
+
595
+ Args:
596
+ nested_list: 嵌套列表
597
+
598
+ Returns:
599
+ 扁平化后的列表
600
+ """
601
+ return CollectionUtils.flatten(nested_list)
602
+
603
+ @staticmethod
604
+ def intersect(*iterables: Iterable) -> List:
605
+ """
606
+ 计算多个可迭代对象的交集
607
+
608
+ Args:
609
+ *iterables: 多个可迭代对象
610
+
611
+ Returns:
612
+ 交集列表
613
+
614
+ Example:
615
+ >>> CollectionUtils.intersect([1, 2, 3], [2, 3, 4], [3, 4, 5])
616
+ [3]
617
+ """
618
+ if not iterables:
619
+ return []
620
+
621
+ result = set(iterables[0])
622
+ for it in iterables[1:]:
623
+ result.intersection_update(it)
624
+
625
+ return list(result)
626
+
627
+ @staticmethod
628
+ def union(*iterables: Iterable) -> List:
629
+ """
630
+ 计算多个可迭代对象的并集
631
+
632
+ Args:
633
+ *iterables: 多个可迭代对象
634
+
635
+ Returns:
636
+ 并集列表
637
+
638
+ Example:
639
+ >>> CollectionUtils.union([1, 2], [2, 3], [3, 4])
640
+ [1, 2, 3, 4]
641
+ """
642
+ result = set()
643
+ for it in iterables:
644
+ result.update(it)
645
+ return list(result)
646
+
647
+ @staticmethod
648
+ def difference(iterable1: Iterable, iterable2: Iterable) -> List:
649
+ """
650
+ 计算两个可迭代对象的差集
651
+
652
+ Args:
653
+ iterable1: 第一个可迭代对象
654
+ iterable2: 第二个可迭代对象
655
+
656
+ Returns:
657
+ 差集列表(在iterable1中但不在iterable2中的元素)
658
+
659
+ Example:
660
+ >>> CollectionUtils.difference([1, 2, 3, 4], [2, 4, 6])
661
+ [1, 3]
662
+ """
663
+ set2 = set(iterable2)
664
+ return [item for item in iterable1 if item not in set2]
665
+
666
+ @staticmethod
667
+ def symmetric_difference(iterable1: Iterable, iterable2: Iterable) -> List:
668
+ """
669
+ 计算两个可迭代对象的对称差集
670
+
671
+ Args:
672
+ iterable1: 第一个可迭代对象
673
+ iterable2: 第二个可迭代对象
674
+
675
+ Returns:
676
+ 对称差集列表(在iterable1或iterable2中但不同时在两者中的元素)
677
+
678
+ Example:
679
+ >>> CollectionUtils.symmetric_difference([1, 2, 3], [2, 3, 4])
680
+ [1, 4]
681
+ """
682
+ set1 = set(iterable1)
683
+ set2 = set(iterable2)
684
+ return list(set1.symmetric_difference(set2))
685
+
686
+ @staticmethod
687
+ def is_subset(iterable1: Iterable, iterable2: Iterable) -> bool:
688
+ """
689
+ 检查iterable1是否是iterable2的子集
690
+
691
+ Args:
692
+ iterable1: 第一个可迭代对象
693
+ iterable2: 第二个可迭代对象
694
+
695
+ Returns:
696
+ iterable1是否是iterable2的子集
697
+
698
+ Example:
699
+ >>> CollectionUtils.is_subset([1, 2], [1, 2, 3])
700
+ True
701
+ """
702
+ return set(iterable1).issubset(iterable2)
703
+
704
+ @staticmethod
705
+ def is_superset(iterable1: Iterable, iterable2: Iterable) -> bool:
706
+ """
707
+ 检查iterable1是否是iterable2的超集
708
+
709
+ Args:
710
+ iterable1: 第一个可迭代对象
711
+ iterable2: 第二个可迭代对象
712
+
713
+ Returns:
714
+ iterable1是否是iterable2的超集
715
+
716
+ Example:
717
+ >>> CollectionUtils.is_superset([1, 2, 3], [1, 2])
718
+ True
719
+ """
720
+ return set(iterable1).issuperset(iterable2)
721
+
722
+ @staticmethod
723
+ def count_elements(iterable: Iterable) -> Dict[Any, int]:
724
+ """
725
+ 计算元素出现次数(与frequency方法相同,提供别名)
726
+
727
+ Args:
728
+ iterable: 可迭代对象
729
+
730
+ Returns:
731
+ 元素出现次数字典
732
+ """
733
+ return CollectionUtils.frequency(iterable)
734
+
735
+ @staticmethod
736
+ def batch_processing(iterable: Iterable, batch_size: int, processor: Callable) -> List:
737
+ """
738
+ 批量处理元素
739
+
740
+ Args:
741
+ iterable: 可迭代对象
742
+ batch_size: 批次大小
743
+ processor: 处理函数
744
+
745
+ Returns:
746
+ 处理结果列表
747
+
748
+ Example:
749
+ >>> CollectionUtils.batch_processing([1, 2, 3, 4, 5], 2, lambda x: sum(x))
750
+ [3, 7, 5]
751
+ """
752
+ result = []
753
+ for batch in CollectionUtils.chunk(iterable, batch_size):
754
+ result.append(processor(batch))
755
+ return result
756
+
757
+