带有if-else语句的Python函数输出错误

为什么我的函数输出不正确?我认为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.

点赞
评论
心的束缚
心的束缚

这行代码:

if 'female' or 'f' or 'woman' or 'famale' or 'women' in gen:

正在评估'women'是否在gen中,但还在评估其他字符串是否为True(它们在逻辑评估器中)。 解决此问题的正确方法是替换以下代码行:

if 'female'  in gen or 'f' in gen or 'woman' in gen or 'famale' in gen or 'women' in gen:
点赞
评论
头碰头
头碰头

When you use or in your if statement, it checks left of the or is a "True" value. When you write if '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_conditions = ['female', 'f', 'woman', 'famale', 'women']
if any([cond in gen for cond in female_conditions]):
    # do something here
点赞
评论
xnam
xnam

这是因为您的表情实际上看起来像这样

('female') or ('f') or ('woman') or ('famale') or ('women' in gen)

由于“ female”不是空字符串,因此输入第一个if块。

您可能想要的是这样的东西:

if any([x in gen for x in ['female', 'f', 'woman', 'famale', 'women']]):
  put = 'female'

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 in gen.

点赞
评论