三元操作符是非常有用的,它爲什麼不以這種特殊情況下工作:Python的三元運算符和分配中的其他
c="d"
d={}
d[c]+=1 if c in d else d[c]=1
它提供:
d[c]+=1 if c in d else d[c]=1
^
SyntaxError: invalid syntax
我看不出有什麼錯這裏因爲沒有三元運算符的同樣的東西可以工作:
c="d"
d={}
if c in d:
d[c]+=1
else:
d[c]=1
對於這種情況,使用defaultdict。 '從集合導入defaultdict; d = defaultdict(int); d [c] + = 1'。 – RemcoGerlich
@RemcoGerlich:當你可以使用'Counter'時,爲什麼要用'defaultdict'來模擬'Counter'? – abarnert
@abarnert:習慣的力量?我總是首先記住'defaultdict',因爲它在'Counter'之前,因爲它更通用。 – user2357112