[英]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
. 我个人喜欢用
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 &
. &
用于设置交集操作,该操作返回一个新set
,其中包含由&
两侧的集合共享的项目。 This will execute the if
block only if there is overlap in gender
and opts
. 只有在
gender
和opts
重叠时才会执行if
块。 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
. 您也可以为您的
elif
重复此过程,创建可能选项列表并检查该列表与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. 另外,正如@Copperfield指出的那样。 You could increase efficiency even more by making the
*_opt
variables (and potentially even gender
sets to begin with: 你可以通过制作
*_opt
变量来提高效率(甚至可能是gender
集开头:
male_opts = {"associé", "gérant", "président", "directeur"}
female_opts = {"associée", "gérante", "présidente", "directrice"}
gender = set(gender)
if male_opts & gender:
...
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
是可迭代的,但是从评论看来它是一个字符串而不是(例如, 'associé gérant'
。虽然此时接受的答案更好,但你仍然可以通过使gender
成为一个来使用这个解决方案组成字符串的单词集:
gender = set(gender.split())
Using lists and any
: 使用列表和
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? 如果你不能在一个
gender
字符串中有多个这些蜇,可能是这样的?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.