在lambda功能中弄平列表

发布于 2025-01-22 13:41:06 字数 237 浏览 3 评论 0原文

我正在尝试构建一个lambda表达式,该表达式以:(a,b [],c),其中b是需要的元素列表被扁平。

例如,表达式的输出应为: (a,b [0],c),(a,b [1],c),(a,b [2],c)...

我尝试研究并寻找与我刚刚描述的情况相似的发电机表达方式,但我无法真正缠绕着这个。

如果有人可以将我指向正确的方向,我会很感激。

I am trying to construct a lambda expression which takes in tuples of the form: (a, b[], c), where b is a list of elements which needs to be flattened.

For example, the output of the expression should be:
(a, b[0], c), (a, b[1], c), (a, b[2], c) ...

I've tried researching and looking for generator expressions that are similar to the situation I've just described, but I can't really wrap my head around this.

I would appreciate it if someone could point me in the right direction.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

划一舟意中人 2025-01-29 13:41:06

您可以使用 itertools.repeats.repeats.repeat() /a>使用zip()b中的每个元素创建所需的元组:

from itertools import repeat

f = lambda a, b, c: zip(repeat(a), b, repeat(c))

print(*f(1, [2, 3, 4], 5))

此输出:

(1, 2, 5) (1, 3, 5) (1, 4, 5)

You can use itertools.repeat() with zip() to create the desired tuple for each element in b:

from itertools import repeat

f = lambda a, b, c: zip(repeat(a), b, repeat(c))

print(*f(1, [2, 3, 4], 5))

This outputs:

(1, 2, 5) (1, 3, 5) (1, 4, 5)
酸甜透明夹心 2025-01-29 13:41:06

返回列表的lambda函数理解列表长度的参数。

func = lambda a, b, c: [(a, b[i], c) for i in range(len(b))]

print(func(1, [2, 3, 4], 5))

A lambda function returning a list comprehension parametrized by the length of the list.

func = lambda a, b, c: [(a, b[i], c) for i in range(len(b))]

print(func(1, [2, 3, 4], 5))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文