`SyntaxError` in if-else one-liner [重复]

问题描述 投票:0回答:2

我写了这块代码,但是因为

SyntaxError
.

它不起作用
def char_freq(message):
    d = dict()
    for ch in message:
        d[ch] += 1 if ch in d else d[ch] = 1
    return d                             ^ SyntaxError: End of statement expected

我不知道如何重写表达式以使 if-else 保持在一行中并使其正常工作。

我知道可以将函数实现为一个简单的

for
循环,但我不明白,为什么我的 if-else 单行代码会导致
SyntaxError

python dictionary if-statement syntax conditional-operator
2个回答
2
投票

d
变成一个 defaultdict 然后你就可以完全忽略这个语句

from collections import defaultdict
def char_freq(message):
    d = defaultdict(int)
    for ch in message:
        d[ch] += 1
    return d     

看起来你只是在数字符,所以你可以使用 counter

from collections import Counter
def char_freq(message):
    return Counter(message)

1
投票

按照你的要求保持

if/else

d[ch] = (d[ch] + 1) if ch in d else 1

但是

dict.get()
语法更好
d[ch] = d.get(ch, 0) + 1

或带有

collections.defaultdict
工厂的
int

def char_freq(message):
    d = defaultdict(int)
    for ch in message:
        d[ch] += 1
    return d
© www.soinside.com 2019 - 2024. All rights reserved.