【问题标题】:In Python, how to map multiple item to one function/value?在 Python 中,如何将多个项目映射到一个函数/值?
【发布时间】:2021-11-02 10:47:54
【问题描述】:

这是演示我的问题的玩具示例 我有多种功能将专门用于我的某些物品

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 = {'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)

输出:

I own cat
I ate cake
I ate pizza
I live in USA

问题是我需要在每种情况下都写 if else 并且我认为如果类别增长它不会很好地扩展。有没有更复杂/pythonic 的方法来处理这个问题?

我也不想写这样的东西

mapping = {'cat':own_pet,
           'dog':own_pet,
           'bird':own_pet,
           'pizza':eat_food,
           ...
            }

for item in random_list:
    mapping[item](item)

我正在考虑类似的事情

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)

逻辑是“如果我的项目在第一个键内,则应用第一个值,依此类推”,反之亦然“如果我的项目在第一个值内,则应用最合适的键,依此类推”

也不一定非要字典,我感觉肯定有比字典更合适的东西

【问题讨论】:

    标签: python function dictionary data-structures mapping


    【解决方案1】:

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

    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
    

    【讨论】:

    • 可能是一个小错字:- 对于 wordlist,func in zip( [animals, food, places], [own_pet, eat_food, live_place] Order 确实有影响...
    • @DanielHao 完成 :)
    • 建议 - 将 value 更改为 key,也许?
    【解决方案2】:

    这是另一种方法。

    尽快:

    mapping = {animal:own_pet,
               food:eat_food,
               place:live_place}
    

    将提高:

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'list'
    

    你最好这样做:

    mapping = {own_pet:animal,
               eat_food:food,
               live_place:place}
    

    然后为了做你想要的,我这样处理:

    random_list = ["cat", "cake", "pizza", "USA"]
    for item in random_list:
        for (thefunction, thelist) in mapping.items():
            if item in thelist:
                thefunction(item)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      • 2021-09-11
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多