根据多种条件设置值

时间:2018-10-17 07:11:42

标签: python-3.x conditional

我正在努力寻找基于多种条件设置对象值的最佳Python方法。我已经进行了很多搜索,但是找不到太多if语句的解决方案,因为它们使我的函数过长。 我正在根据字符串列表中存在的单词的不同键设置gender的值。

details = ["Women", "Shoes"]

if 'Men' in details:
    gender = 'men'
elif 'Women' in details:
    gender = 'Women'
elif 'girl' in details:
    gender = 'girl'
elif 'boy' in details:
    gender = 'boy'
......

如何简短?

1 个答案:

答案 0 :(得分:0)

details = ["Women", "Shoes"]
maps = {"Men": "men", "girl": "girl", "Women": "Women", "boy": "boy"}
for key in maps.keys():
    if key in details:
        gender = maps.get(key, None)