你能用参数元组创建方法吗?
Can you create method with tuple of parameters?
你能在 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")
预期输出:
“你最喜欢的食物是披萨、意大利面和冰淇淋”
“你最喜欢的颜色是黑色、蓝色和绿色”
当然-
您的操作方式如下:
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")
)
你能在 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")
预期输出:
“你最喜欢的食物是披萨、意大利面和冰淇淋”
“你最喜欢的颜色是黑色、蓝色和绿色”
当然- 您的操作方式如下:
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")
)