如何在 Python 中使用 pyDash 映射数组元素
How to map element of an array using pyDash in Python
我正在尝试链接和分组而不是使用 pydash 映射数组
想法是重新创建此 lodash 函数的相同输出:
let chainedResult = (
_.chain(oResult)
// Group the elements of the result based on `CEMPLOYEE` property
.groupBy("CCALENDAR_WEEK")
// `key` is group's name (CEMPLOYEE), `value` is the array of objects
.map((value, key) => ({
WEEK: key,
Capacity: value
}))
).value();
到目前为止,这是我取得的成就
_.chain(empCapacity).group_by(lambda dt:dt["CCALENDAR_WEEK"]).value()
我卡在这里了,关于如何映射键和值?如何使用 pydash 在 python 中执行以下代码?
.map((value, key) => ({
WEEK: key,
Capacity: value
}))
期望输出:
你试过只使用 .map()
吗? The docs say:
The iteratee is invoked with three arguments: (value, index|key, collection).
因为这似乎是直接从 lodash 文档中复制的。在 python 中,它足够聪明地检查“iteratee”的签名(即你传递给 .map()
的函数),否则这会崩溃,因为在 python 中你不能传递额外的参数到一个不期望它们的函数。
所以这对我有用:
from pydash import py_
my_entries = [
{'name': 'barney', 'food': 'jelly'},
{'name': 'bill', 'food': 'jelly'},
{'name': 'buster', 'food': 'aubergine'},
]
(
py_(my_entries)
.group_by('food')
.map(lambda value, key: (key, value))
).value()
给出:
[
(
'jelly',
[
{'name': 'barney', 'food': 'jelly'},
{'name': 'bill', 'food': 'jelly'},
]
),
(
'aubergine',
[
{'name': 'buster', 'food': 'aubergine'}
]
)
]
我正在尝试链接和分组而不是使用 pydash 映射数组
想法是重新创建此 lodash 函数的相同输出:
let chainedResult = (
_.chain(oResult)
// Group the elements of the result based on `CEMPLOYEE` property
.groupBy("CCALENDAR_WEEK")
// `key` is group's name (CEMPLOYEE), `value` is the array of objects
.map((value, key) => ({
WEEK: key,
Capacity: value
}))
).value();
到目前为止,这是我取得的成就
_.chain(empCapacity).group_by(lambda dt:dt["CCALENDAR_WEEK"]).value()
我卡在这里了,关于如何映射键和值?如何使用 pydash 在 python 中执行以下代码?
.map((value, key) => ({
WEEK: key,
Capacity: value
}))
期望输出:
你试过只使用 .map()
吗? The docs say:
The iteratee is invoked with three arguments: (value, index|key, collection).
因为这似乎是直接从 lodash 文档中复制的。在 python 中,它足够聪明地检查“iteratee”的签名(即你传递给 .map()
的函数),否则这会崩溃,因为在 python 中你不能传递额外的参数到一个不期望它们的函数。
所以这对我有用:
from pydash import py_
my_entries = [
{'name': 'barney', 'food': 'jelly'},
{'name': 'bill', 'food': 'jelly'},
{'name': 'buster', 'food': 'aubergine'},
]
(
py_(my_entries)
.group_by('food')
.map(lambda value, key: (key, value))
).value()
给出:
[
(
'jelly',
[
{'name': 'barney', 'food': 'jelly'},
{'name': 'bill', 'food': 'jelly'},
]
),
(
'aubergine',
[
{'name': 'buster', 'food': 'aubergine'}
]
)
]