通过Lambda X功能改进(缩短)我的列表理解?

发布于 2025-01-28 10:30:49 字数 385 浏览 2 评论 0原文

!!!我知道我可以在这里使用counter(),但这不是重点!

给出以下代码:

test =[['a',1],['a',2],['b',3], ['c',5],['a',7],['c',9]]

{i:[test[x][0] for x in range(len(test))].count(i) for i in [test[x][0] for x in range(len(test))]}

output: {'a': 3, 'b': 1, 'c': 2}

有没有办法避免在不创建另一个变量的情况下重复序列:

[test[x][0] for x in range(len(test))]

!!! I know I could use Counter() here, but that's not the point !!!

Giving the code below:

test =[['a',1],['a',2],['b',3], ['c',5],['a',7],['c',9]]

{i:[test[x][0] for x in range(len(test))].count(i) for i in [test[x][0] for x in range(len(test))]}

output: {'a': 3, 'b': 1, 'c': 2}

Is there a way to avoid repeating the sequence without creating another variable:

[test[x][0] for x in range(len(test))]

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

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

发布评论

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

评论(1

萌梦深 2025-02-04 10:30:49
from itertools import groupby

test =[['a',1],['a',2],['b',3], ['c',5],['a',7],['c',9]]

{key: sum(j[1] for j in i) for key, i in groupby(test, key=lambda x: x[0])}
from itertools import groupby

test =[['a',1],['a',2],['b',3], ['c',5],['a',7],['c',9]]

{key: sum(j[1] for j in i) for key, i in groupby(test, key=lambda x: x[0])}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文