简体   繁体   中英

Ternary operator python not working on dict assignment

I'm new to python.

Today i'm trying to simplify this:

        for x in t:
            if x in hash:
                hash[x] += 1
            else:
                hash[x] = 1

To this:

        for x in t:
            hash[x] += 1 if x in hash else hash[x] = 1

Then i got an error:

SyntaxError: invalid syntax
                                           ^
    hash[x] += 1 if x in hash else hash[x] = 1
Line 8  (Solution.py)

I thought i'm doing an expression here? as shown in this question

What am i doing wrong?

The ternary operator returns a value, it does not support an assignment as a value (otherwise it would be a regular if/then/else)

You can use it like this:

hash[x] = hash[x] + 1 if x in hash else 1

BTW hash is a Python built-in function, you should not use that as a variable name.

Note that there are other data structures in Python that might be better suited to your purpose. (eg collections.Counter, collections.defaultdict)

Try this:

for x in t:
    hash[x] = hash.get(x, 0) + 1 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM