简体   繁体   中英

Find a more efficient way to code an If statement in python

it's the second time I'm confronted to this kind of code :

    if "associé" in gender or "gérant" in gender or "président" in gender or "directeur" in gender:
    gen = "male"
elif "associée" in gender or "gérante" in gender or "présidente" in gender or "directrice" in gender:
    gen = "female"
else:
    gen = "error"

I'd like to find a more efficient way to write this code because it looks really bad.

I personally like doing this with sets . For example:

opts = ["associé", "gérant", "président", "directeur"]


if set(opts) & set(gender):
...

& is used for the set intersection operation which returns a new set with the items shared by the sets on either side of the & . This will execute the if block only if there is overlap in gender and opts . You can repeat the process for your elif as well, creating a list of the possible options and checking for overlap between that list and gender . All together, you could do something like this:

male_opts = ["associé", "gérant", "président", "directeur"]
female_opts = ["associée", "gérante", "présidente", "directrice"]

if set(male_opts) & set(gender):
    gen = "male"
elif set(female_opts) & set(gender):
    gen = "female"
else:
    gen = "error"

Also, as @Copperfield points out. You could increase efficiency even more by making the *_opt variables (and potentially even gender sets to begin with:

male_opts = {"associé", "gérant", "président", "directeur"}
female_opts = {"associée", "gérante", "présidente", "directrice"}
gender = set(gender)

if male_opts & gender:
...

Edit:

The code above assumes that gender is an iterable, but it seems from the comments that it is a string instead (eg, 'associé gérant' . Although the accepted answer is better at this point, you could still use this solution by making gender a set of the words that make up the string:

gender = set(gender.split())

Using lists and any :

males = ["associé", "gérant", "président", "directeur"]
females = ["associée", "gérante", "présidente", "directrice"]

if any(m in gender for m in males):
    gen = "male"
elif any(m in gender for m in females):
    gen = "female"
else:
    gen = "Error"

If you cannot have multiple of these stings in one gender string, maybe something like this?

gen = "error"
for g in ["associé", "gérant", "président", "directeur"]:
    if g in gender:
        gen = "male"
        break
for g in ["associée" "gérante", "présidente", "directrice"]:
    if g in gender:
        gen = "female"
        break

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