我正在尝试使用 dict 理解和 python 中的三元运算来执行以下表达式:
for num in ar:
if num in seen_dict:
seen_dict[num] += 1
else:
seen_dict[num] = 1
我试过这个:
seen_dict = { num: seen_dict[num] += 1 for num in ar if num in seen_dict else seen_dict[num] = 1}
及其几个排列,但我不断收到语法错误。可以做我想做的吗?
更新
这是正确的语法,但不是我的 dict 只返回 1: seen_dict = { num: (seen_dict[num] + 1) if num in seen_dict else 1 for num in ar }
有人可以解释为什么这与 for 循环的功能不同吗?谢谢你。
红颜莎娜
慕姐4208626
相关分类