'Is there any similar collection library, such as distinctBy, groupBy in python? [closed]
the example is in Kotlin language. I think these functions are very convinient and very popular, so maybe there was one there in python?
/*
the example is in Kotlin language
*/
val list = listOf(1, 2, 3, 5, 4)
assert(list.distinctBy { it % 3 } == listOf(1, 2, 3))
println(list.groupBy({ t -> t % 3 }, { t -> t * t }))
// print: {1=[1, 16], 2=[4, 25], 0=[9]}
Solution 1:[1]
Inferring what those function do from the example:
>>> l = [1, 2, 3, 5, 4]
>>> {it % 3 for it in l} # make a set
{0, 1, 2}
>>> {(t % 3): (t * t) for t in l}
{1: 16, 2: 25, 0: 9}
>>> d = {}
>>> for t in l:
... d.setdefault(t % 3, []).append(t * t) # accumulate in dictionary entries
...
>>> d
{1: [1, 16], 2: [4, 25], 0: [9]}
Solution 2:[2]
Actually I think it is necessary to make a library to do such things. I can find something similar in java, javascript, c#, dart, etc Just list comprehensions or map comprehensions is not enough anyway.
def distinctBy(a, fv):
b = OrderedDict()
for x in a:
b.setdefault(fv(x), x)
return list(b.values())
def groupBy(a, fk, fv):
b = OrderedDict()
for x in a:
b.setdefault(fk(x), []).append(fv(x))
return b
a = [1, 2, 3, 5, 4]
assert distinctBy(a, lambda x: x % 3) == [1, 2, 3]
print(groupBy(a, lambda x: x % 3, lambda x: x*x))
# print: OrderedDict([(1, [1, 16]), (2, [4, 25]), (0, [9])])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jerry101 |
Solution 2 | dikinova |