python - In Python, how to map multiple item to one function/value?
问题描述
Here is the toy example to demonstrate my problem I have multiple function which will be used exclusively on some of my item
def eat_food(item):
print(f'I ate {item}')
def own_pet(item):
print(f'I own {item}')
def live_place(item):
print(f'I live in {item}')
Here is the correspoding item
animal = ['cat', 'dog', 'bird']
food = ['pizza', 'ham', 'cake']
place = ['Italy', 'USA', 'Malaysia']
I want to apply these functions only on the appropriate item something like
mapping = {'animal':own_pet,
'food':eat_food,
'place':live_place}
random_list = ['cat', 'cake', 'pizza', 'USA']
for item in random_list:
if item in animal:
apply_function = 'animal'
elif item in food:
apply_function = 'food'
elif item in place:
apply_function = 'place'
mapping[apply_function](item)
output:
I own cat
I ate cake
I ate pizza
I live in USA
The problem is that I need to write if else on every condition and I think it won't scale well if the categories grow. Are there any more sophisciated/pythonic ways to deal with this?
I also don't wanna write out something like this
mapping = {'cat':own_pet,
'dog':own_pet,
'bird':own_pet,
'pizza':eat_food,
...
}
for item in random_list:
mapping[item](item)
I'm thinking about something like
mapping = {animal:own_pet,
food:eat_food,
place:live_place}
# Translate into this
# mapping = {['cat', 'dog', 'bird']:own_pet,
# ['pizza', 'ham', 'cake']:eat_food,
# ['Italy', 'USA', 'Malaysia']:live_place}
random_list = ['cat', 'cake', 'pizza', 'USA']
for item in random_list:
mapping[`***some mysterious technique***`](item)
The logic is that "if my item is inside the first key, then apply the first value, and so on" or vice versa "if my item inside the first value, apply the fitst key, and so on"
It doesn't have to be a dictionary either, I have a feeling that there must be something suitable than using dictionary
解决方案
它可以是字典,但键可以是列表和值函数中的单个单词。例如:
def eat_food(item):
print(f"I ate {item}")
def own_pet(item):
print(f"I own {item}")
def live_place(item):
print(f"I live in {item}")
animal = ["cat", "dog", "bird"]
food = ["pizza", "ham", "cake"]
place = ["Italy", "USA", "Malaysia"]
mapping = {
word: func
for wordlist, func in zip(
[animal, food, place], [own_pet, eat_food, live_place]
)
for word in wordlist
}
random_list = ["cat", "cake", "pizza", "USA", "xxx"]
for value in random_list:
mapping.get(value, lambda x: None)(value)
印刷:
I own cat
I ate cake
I ate pizza
I live in USA
推荐阅读
- html - 在 svg 中实现 'Bowtie' 类型的文本
- r - 使用相同的日期字段列计算日期差异
- asp.net-mvc-5 - ASP.NET MVC 5 双重身份验证类型
- java - 使用 mvn post-clean install 比使用 mvn clean install 更好吗?
- html - CSS 相对位置 left 有效,但 top 无效
- javascript - 如何使用 pm2 每 5 秒运行一次 JS 脚本
- android - 为什么不能从字符串转换为int?
- angular - Angular从客户端避免CORS问题
- sql - 通过 DENSE_RANK() 在 partition by 和 order by 中使用相同的列
- jenkins - Jenkins 不调用 psexec 命令,因为“访问被拒绝”