Python 动态参数用元祖和字典做函数输入参数的例子

本文通过实例介绍了Python中*args与**kwargs的功能与使用方法。重点解释了这两种参数如何帮助函数接受不定数量的位置参数和关键字参数,并展示了混合使用两种参数的方式。

一直好奇函数定义里的*args *kwargs是怎么实现的, 查阅资料后自己写了一个例子. 注意一下这里 pKeys=list(para.keys()) , 字典的keys返回类型是 dict_list, 必须用list()进行转换,否则不能调用.

注意 *args和 *kwargs 必须放最后, 要不提示语法错误


# 动态参数
def TuplePara_add(*args):
    ''' 只用元祖做参数'''
    result =  args[0]+args[1]
    return result

def DictPara_add(**args):
    ''' 只用字典做参数'''
    return args["x"] + args["y"]

def dict_tuple_mixed_para(*args,**kwargs):
    ''' 元祖与字典混合参数 '''
    para={'x':0 , 'y':0 , 'z':0}
    pKeys=list(para.keys())
    
    if args:
        for i in range(0,len(args)):
            KeyStr= pKeys[i]
            para[KeyStr] = args [i]
    if kwargs:
        kwKeyList= list(kwargs.keys())
        for i in range (0, len(kwargs)):
            KeyStr = kwKeyList[i]
            para[KeyStr] = kwargs [KeyStr]
    print(f'元祖与字典混合输入参数 x:{para["x"]} y:{para["y"] } z:{ para["z"]}')
    return para['x'] + para['y'] + para['z']

if __name__ == "__main__":
    print(f"Tuple参数函数返回:{TuplePara_add(2,3)}")
    print(f"字典参数函数返回: { DictPara_add(x=6,y=9)}")

    print(f'混合参数一:{dict_tuple_mixed_para(5,9,z=12)}')      # 显示 x,y,z 的值
    print(f'混合参数二:{dict_tuple_mixed_para(5,9,x=12)}')      # 只显示 x,y 的值
    # print(f'混合参数三:{dict_tuple_mixed_para(x=5,9,12)}')      # 语法错误

返回结果

Tuple参数函数返回:5
字典参数函数返回: 15
元祖与字典混合输入参数 x:5 y:9 z:12
混合参数一:26
元祖与字典混合输入参数 x:12 y:9 z:0
混合参数二:21

 

### Python 中关于元组字典的练习题 以下是几个涉及 Python 元组字典的经典练习题及其解答: #### 练习题 1:统计字符串中的大小写字母数量 编写一个函数 `fun`,接收一个字符串参数,返回一个元组 `(upper_count, lower_count)`,其中第一个值表示大写字母的数量,第二个值表示小写字母的数量。 ```python def fun(x): upper_count = 0 lower_count = 0 for item in x: if item.isupper(): upper_count += 1 elif item.islower(): lower_count += 1 else: continue return upper_count, lower_count result = fun('ehllo WROLD') print(result) # 输出应为 (5, 5)[^1] ``` --- #### 练习题 2:创建菜单字典并打印键值对 通过用户输入动态创建一个菜单字典 `menu_dict`,其键为食物名称,值为其对应的价格。最后分别打印所有的键值。 ```python menu_dict = {} while True: try: food = input("请输入食物名称(单独回车结束):") if not food.strip(): # 如果输入为空,则退出循环 break price = int(input("请输入价格:")) menu_dict[food] = price except ValueError: print("输入有误,请重新输入!") for k in menu_dict.keys(): # 打印所有键 print(f"食物名称: {k}") for v in menu_dict.values(): # 打印所有值 print(f"价格: {v}") ``` 此代码片段展示了如何利用异常处理机制来捕获非法输入,并实现动态构建字典的功能[^2]。 --- #### 练习题 3:查找特定模式的元素 给定三个容器(列表、元组、字典),找出以字母 `'a'` 或 `'A'` 开头且以 `'c'` 结尾的所有元素。 ```python li = ["alec", "aric", "Alex", "Tony", "rain"] tu = ("alec", "aric", "Alex", "Tony", "rain") dic = {'k1': "alex", 'k2': 'aric', "k3": "Alex", "k4": "Tony"} list1 = list(tu) list2 = list(dic.values()) newlist = li + list1 + list2 results = [] for i in newlist: stripped_i = i.strip() if (stripped_i.startswith('a') or stripped_i.startswith('A')) and stripped_i.endswith('c'): results.append(stripped_i) print(results) # 输出 ['alec', 'aric', 'alec', 'aric', 'aric'][^3] ``` --- #### 练习题 4:去除重复项的方法比较 提供两种方法用于从列表中去除重复项,一种基于字典去重,另一种基于集合去重。 ##### 方法一:使用字典去重 ```python a_list = [1, 1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 3, 5, 2] a_dic = {key: 0 for key in a_list} ans = list(a_dic.keys()) print(ans) # 输出 [1, 2, 3, 4, 5, 6, 7][^4] ``` ##### 方法二:使用集合去重 ```python a_list = [1, 1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 3, 5, 2] ans = list(set(a_list)) print(ans) # 输出可能顺序不同,如 [1, 2, 3, 4, 5, 6, 7][^4] ``` --- #### 练习题 5:将数值分类存储到字典中 将一组整数分为两类,一类存入字典的一个键对应的值列表中,另一类存入另一个键对应的值列表中。 ```python data = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90] dictionary = {} greater_than_66 = [] less_than_66 = [] for value in data: if value > 66: greater_than_66.append(value) elif value < 66: less_than_66.append(value) dictionary['k1'] = greater_than_66 dictionary['k2'] = less_than_66 print(dictionary) # 输出 {'k1': [77, 88, 99, 90], 'k2': [11, 22, 33, 44, 55]}[^5] ``` --- #### 练习题 6:模拟购物程序 设计一个简单的购物车功能,允许用户选择商品加入购物车,并判断总金额是否超出预算。 ```python goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "美女", "price": 998}, ] total_assets = int(input("请输入您的总资产:")) shopping_cart = {} cart_total_price = 0 for idx, product in enumerate(goods, start=1): shopping_cart[idx] = product["name"] print(shopping_cart) while True: choice = int(input("请选择要购买的商品编号(输入0结束选购):")) if choice == 0: break selected_product_name = shopping_cart.get(choice) if selected_product_name is None: print("无效的选择,请重新输入!") continue selected_product_price = next(item["price"] for item in goods if item["name"] == selected_product_name) cart_total_price += selected_product_price print(f"已将{selected_product_name}加入购物车,总价目前为{cart_total_price}") if cart_total_price > total_assets: print("余额不足,无法完成购买!") else: print("购买成功!感谢惠顾!")[^5] ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值