首页 > 解决方案 > 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

标签: pythonfunctiondictionarydata-structuresmapping

解决方案


它可以是字典,但键可以是列表和值函数中的单个单词。例如:

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

推荐阅读