【发布时间】:2023-03-29 10:04:02
【问题描述】:
counts = defaultdict(int)
for elem in sets: #list of sets
for _ in elem: #each set contains elements that may be duplicates among the sets
counts[_] += 1
有没有办法对这样的代码使用字典理解?
【问题讨论】:
-
给出样本输入输出
-
您能解释一下为什么要为此使用 list-comp 吗?你的帖子的标题和帖子的正文有些矛盾。 list-comp 的结果是
list- 你正在做的是想要一个dict似乎...... -
IndentationError - 这是你的问题吗? minimal reproducible example, How to Ask
-
通常你不想使用列表推导来获得“副作用”——如果你想要一个列表结果就使用它们。对于其他任何事情 - 使用循环 - 而不是创建您不想要的列表的副作用。
-
题外话,但是
_作为变量名的常规用法是for a throwaway,所以这里用起来比较混乱。
标签: python list-comprehension dictionary-comprehension