python - 你能用参数元组创建方法吗?
问题描述
你能在 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 - 如何在熊猫数据框中添加计算列?
- python - 有没有办法在opencv python中同时获得主流和子流
- php - 如何制作一个可以获取订单的 Woocommerce php 插件
- python - 添加 Dropout 后,运行时间从每 epoch 约 10 秒增加到每 epoch 约 120 秒?
- angular - 如何在带有 Ionic 选项卡的 Angular 应用程序中使用路由?
- python - django.core.exceptions.FieldError:为 TblDetails 指定了未知字段(类别)?
- github - 如何使用 GitHub Actions 将标签部署到 Netlify?
- python - 如何在python中修复字符串长度
- react-redux - 如何与 Redux 一起在 react-testing-library 中传递来自 react-i18next 的 i18n 翻译对象?
- firebase - 有没有办法将外部 API 数据导入 Firebase 数据库?