[英]Ternary Operator with a dictionary [python]
I want to optimize the code below to a one line我想将下面的代码优化为一行
if i == 0:
d = {}
else:
d[j] = d.get(j, 0) + 1
i tried solving it using a ternary operator but it gave me an error我尝试使用三元运算符解决它,但它给了我一个错误
d = {} if i == 0 else d[j] = d.get(j, 0) + 1
The error :错误 :
d = {} if i == 0 else d[j] = d.get(j, 0) + 1 ^ SyntaxError: cannot assign to conditional expression
Can it be solved using ternary operator or is there another way to make it in a one line ?它可以使用三元运算符解决还是有另一种方法可以将其放在一行中?
For reference, here is a one liner.作为参考,这是一个单衬。 I wouldn't call it an improvement though as your original
if
/ else
method is much more readable:我不会称之为改进,因为您原来的
if
/ else
方法更具可读性:
d = {} if i == 0 else {**d, j: d.get(j, 0) + 1}
Starting with Python 3.9 you can do the following:从 Python 3.9 开始,您可以执行以下操作:
d = {} if i == 0 else d | {j: d.get(j, 0) + 1}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.