首页 > 解决方案 > 你能用参数元组创建方法吗?

问题描述

你能在 Python 中做这样的事情吗?

def give_me_your_three_favorite_things_in_each_given_category(
    food=(first, second, third), 
    color=(first, second, third))
    println(f"Your favorite foods are {food.first}, {food.second} and {food.third}")
    println(f"Your favorite colors are {color.first}, {color.second} and {color.third}")

give_me_your_three_favorite_things_in_each_given_category(
    food=(first="pizza", second="pasta", third="ice cream"),
    color=(first="black", second="blue", third="green")

预期输出:
“你最喜欢的食物是披萨、意大利面和冰淇淋”
“你最喜欢的颜色是黑色、蓝色和绿色”

标签: pythonpython-3.xmethodsparametersparameter-passing

解决方案


当然 - 你会这样做的方式如下:

def give_me_your_three_favorite_things_in_each_given_category(food, color):
    first_food, second_food, third_food = food
    print(f"Your favorite foods are {first_food}, {second_food}, {third_food}")
    first_color, second_color, third_color = color
    print(f"Your favorite colors are {first_color}, {second_color}, {third_color}")

你可以在这里看到我们接收元组作为参数,然后解包它们。

然后,您可以使用

give_me_your_three_favorite_things_in_each_given_category(
food=("pizza", "pasta", "ice cream"),
color=("black", "blue", "green"))

您还可以使用命名元组,以便您可以为元组中的每个值命名:

from collections import namedtuple
Food = namedtuple("Food", ("first", "second", "third"))
Color = namedtuple("Color", ("first", "second", "third"))
give_me_your_three_favorite_things_in_each_given_category(
    food=Food(first="pizza", second="pasta", third="ice cream"),
    color=Color(first="black", second="blue", third="green")
)

推荐阅读