为什么我的函数输出不正确?我认为if-else语句但idk出现了问题。
def standardize_gender(gen):
gen = gen.strip()
gen = gen.lower()
if 'female' or 'f' or 'woman' or 'famale' or 'women' in gen:
put = 'female'
elif 'male' or 'man' or 'm' or 'men' in gen:
put = 'male'
elif 'nonbinary' or 'transgender' in gen:
put = 'nonbinary_or_trans'
else:
put = np.nan
return put
standardize_gender('male') #Outputs 'female'
Your 'or' statement is wrong - you have to do something like
if 'female' in gen or if 'woman' in gen...
, (each individually). Yours is basically saying "if 'female'", which would be considered true.这行代码:
正在评估'women'是否在gen中,但还在评估其他字符串是否为True(它们在逻辑评估器中)。 解决此问题的正确方法是替换以下代码行:
When you use
or
in your if statement, it checks left of the or is a "True" value. When you writeif 'female':
in python, a string is a "True" type and program continue to evaluate code in the if statement. This is why you are getting "female" all the time. To avoid this, you can use:这是因为您的表情实际上看起来像这样
由于“ female”不是空字符串,因此输入第一个if块。
您可能想要的是这样的东西:
The
any
function takes an iterable of booleans and returns true if any one of them is true. The for comprehension (everything inside the first pair of square brackets) provides that list of booleans by going through every element in the list['female', 'f', 'woman', 'famale', 'women']
and checking if that element (x
) is present ingen
.