我正在努力寻找基于多种条件设置对象值的最佳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'
......
如何简短?
答案 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)