python使用技巧(二十五):*args, **kwargs生成可变列表与字典
2023-09-14 09:15:32 时间
def func(*args, **kwargs):
"""
*args用来表示函数接收可变长度的非关键字参数列表作为函数的输入
**kwargs表示函数接收可变长度的关键字参数字典作为函数的输入**kwargs表示函数接收可变长度的关键字参数字典作为函数的输入
"""
print(args)
print(kwargs)
print("------------------")
return args
def test_args(normal_arg, *args):
print("first normal arg:" + normal_arg)
for arg in args:
print("another arg through *args :" + arg)
def test_kwargs(**kwargs):
if kwargs is not None:
for key, value in kwargs.items():
print("{} = {}".format(key,value))
# Or you can visit kwargs like a dict() object
# for key in kwargs:
# print("{} = {}".format(key, kwargs[key]))
if __name__ == "__main__":
func()
func(1, 2, 3, 4)
func(A=1, B=2, C=3)
func("python", 123, A=1, B=2, C=3)
list1 = [1,2,3]
list2 = [3,5,6]
list3 = [9,10]
# func(list1)
func(list1,list2)
print("func1--->",list(func(list1,list2,list3)))
print("func2--->", func(list1, list2, list3))
test_args("normal", "python", "java", "C#")
test_kwargs(name="python", value="5")
生成结果:
()
{}
------------------
(1, 2, 3, 4)
{}
------------------
()
{'A': 1, 'B': 2, 'C': 3}
------------------
('python', 123)
{'A': 1, 'B': 2, 'C': 3}
------------------
([1, 2, 3], [3, 5, 6])
{}
------------------
([1, 2, 3], [3, 5, 6], [9, 10])
{}
------------------
func1---> [[1, 2, 3], [3, 5, 6], [9, 10]]
([1, 2, 3], [3, 5, 6], [9, 10])
{}
------------------
func2---> ([1, 2, 3], [3, 5, 6], [9, 10])
first normal arg:normal
another arg through *args :python
another arg through *args :java
another arg through *args :C#
name = python
value = 5
相关文章
- Python-装饰器-案例-获取文件列表
- Python命令行参数解析模块getopt使用实例
- Python - 搭建Jupyter notebook环境
- Python 关于“列表去重”的几点小技巧
- 已解决2.Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python (but this will use pure-Python parsing and wi
- 已解决Visit python.org to download an earlier version of Python.
- Python小数据保存,有多少中分类?不妨看看他们的类比与推荐方案...
- Python爬虫:url中带字典列表参数的编码转换
- python 某个目录下的所有文件列表
- python列表和QVariant
- 使用 Consul 作为 Python 微服务的配置中心
- 【python中级】 list列表实现Queue队列先进先出的功能
- 〖Python全栈白宝书-免费版㉒〗- Python列表常用方法
- Python少儿编程提高篇(2)列表