当前位置:   article > 正文

Python中的*(星号)和**(双星号)完全详解_python运算符**

python运算符**

在Python中,*和**是两个重要的运算符,它们具有不同的用途。

*(星号)用于解包序列或可迭代对象,将其元素分配给函数的参数或在列表、元组等数据结构中进行拼接。

**(双星号)用于解包字典,将其键值对传递给函数的参数或在字典中进行拼接。

【示例代码】

下面是在实际接口自动化工作中常见的示例代码,演示了*和**的使用。

使用*解包序列或可迭代对象

  1. # 示例:传递可变数量的参数
  2. def sum_values(*args):
  3. total = 0
  4. for num in args:
  5. total += num
  6. return total
  7. result = sum_values(1, 2, 3, 4, 5)
  8. print(result) # 输出:15
  9. # 示例:拼接列表
  10. numbers = [1, 2, 3, 4, 5]
  11. result = [*numbers, 6, 7, 8]
  12. print(result) # 输出:[1, 2, 3, 4, 5, 6, 7, 8]
  13. # 使用**解包字典
  14. # 示例1:传递可变数量的关键字参数
  15. def print_info(**kwargs):
  16. for key, value in kwargs.items():
  17. print(key, ":", value)
  18. print_info(name="Alice", age=25, city="New York")
  19. # 输出:
  20. # name : Alice
  21. # age : 25
  22. # city : New York
  23. # 示例:拼接字典
  24. defaults = {"color": "red", "size": "medium"}
  25. user_preferences = {"size": "large", "theme": "dark"}
  26. result = {**defaults, **user_preferences}
  27. print(result)
  28. # 输出:{'color': 'red', 'size': 'large', 'theme': 'dark'}

这些示例代码展示了*和**的基本用法。它们在接口自动化工作中可以用于传递可变数量的参数或关键字参数,以及在数据结构中进行拼接操作。

【*(星号)的用途】

函数参数解包:当你有一个包含多个元素的列表或元组时,可以使用*将其解包,并将每个元素作为单独的参数传递给函数。

  1. # 示例代码:
  2. def multiply(a, b, c):
  3. return a * b * c
  4. numbers = [2, 3, 4]
  5. result = multiply(*numbers)
  6. print(result) # 输出:24
  7. # 序列解包:使用*可以将一个序列解包到另一个序列中。
  8. # 示例代码:
  9. numbers = [1, 2, 3]
  10. new_numbers = [*numbers, 4, 5, 6]
  11. print(new_numbers) # 输出:[1, 2, 3, 4, 5, 6]
  12. 可变数量的参数:在函数定义时,*args可以接受可变数量的参数,这些参数被封装为一个元组。
  13. # 示例代码:
  14. def calculate_sum(*args):
  15. total = 0
  16. for num in args:
  17. total += num
  18. return total
  19. result = calculate_sum(1, 2, 3, 4, 5)
  20. print(result) # 输出:15

【**(双星号)的用途】

字典解包:使用**可以将字典解包为关键字参数,将键值对传递给函数。

  1. # 示例代码:
  2. def print_info(name, age, city):
  3. print("Name:", name)
  4. print("Age:", age)
  5. print("City:", city)
  6. user_info = {"name": "Alice", "age": 25, "city": "New York"}
  7. print_info(**user_info)
  8. # 输出:
  9. # Name: Alice
  10. # Age: 25
  11. # City: New York
  12. 字典拼接:使用**可以将多个字典进行拼接。
  13. # 示例代码:
  14. defaults = {"color": "red", "size": "medium"}
  15. user_preferences = {"size": "large", "theme": "dark"}
  16. result = {**defaults, **user_preferences}
  17. print(result)
  18. # 输出:{'color': 'red', 'size': 'large', 'theme': 'dark'}

可变数量的关键字参数:在函数定义时,**kwargs可以接受可变数量的关键字参数,这些参数被封装为一个字典。

  1. # 示例代码:
  2. def print_info(**kwargs):
  3. for key, value in kwargs.items():
  4. print(key, ":", value)
  5. print_info(name="Alice", age=25, city="New York")
  6. # 输出:
  7. # name : Alice
  8. # age : 25
  9. # city : New York

【应用场景】

*和**在接口自动化工作中具有广泛的应用。它们可以帮助我们处理可变数量的参数、解包数据结构、动态构建函数调用等。

例如,在发送HTTP请求时,我们经常需要传递不同数量和类型的参数。使用*和**可以根据需要动态传递参数,而无需事先确定参数的数量。

  1. # 示例代码:
  2. import requests
  3. def send_request(url, method="GET", **kwargs):
  4. response = requests.request(method, url, **kwargs)
  5. return response
  6. # 发送GET请求
  7. response1 = send_request("https://api.example.com/data")
  8. # 发送POST请求
  9. data = {"username": "Alice", "password": "123456"}
  10. response2 = send_request("https://api.example.com/login", method="POST", json=data)

在这个例子中,我们定义了一个send_request函数,它可以根据需要传递不同的参数。通过使用**kwargs,我们可以在函数调用时灵活地传递各种关键字参数,例如headers、params、json等。

请注意,和**还可以用于其他更复杂的情况,例如在函数定义时使用args和kwargs来接受不定数量的参数,或者在函数调用时使用*和来传递已经打包好的参数。此外,*和**还在迭代器和生成器中有其他的应用场景。

【*在迭代器和生成器中的作用】

在迭代器和生成器中,*用于展开可迭代对象并将其作为单独的元素进行处理。

  1. # 示例代码:
  2. # 迭代器示例
  3. numbers = [1, 2, 3, 4, 5]
  4. iterator = iter(numbers)
  5. first, *rest = iterator
  6. print(first) # 输出:1
  7. print(rest) # 输出:[2, 3, 4, 5]
  8. # 生成器示例
  9. def generate_numbers():
  10. yield from range(1, 6)
  11. first, *rest = generate_numbers()
  12. print(first) # 输出:1
  13. print(rest) # 输出:[2, 3, 4, 5]

在这个例子中,我们使用*将可迭代对象(numbers和generate_numbers())中的元素展开,并将第一个元素赋值给变量first,将剩余的元素赋值给变量rest。

【**在迭代器和生成器中的作用】

在迭代器和生成器中,**用于接收和传递关键字参数。

  1. # 示例代码:
  2. # 迭代器示例
  3. def iterate_dict():
  4. yield {"name": "Alice", "age": 25}
  5. data = next(iterate_dict())
  6. print(data) # 输出:{'name': 'Alice', 'age': 25}
  7. # 生成器示例
  8. def generate_dict():
  9. yield {"name": "Bob", "age": 30}
  10. data = next(generate_dict())
  11. print(data) # 输出:{'name': 'Bob', 'age': 30}

在这个例子中,我们使用**将关键字参数作为字典进行传递,并在迭代器和生成器中生成包含关键字参数的字典对象。

【应用场景】

在实际的接口自动化工作中,我们经常需要处理迭代器和生成器来处理大量的数据或实现惰性计算。*和**在这些场景中非常有用,可以帮助我们处理迭代器和生成器中的元素和关键字参数。

例如,在处理API响应数据时,我们可以使用迭代器和生成器来逐个处理返回的结果。同时,使用*可以将这些结果展开并进行进一步的处理,而使用**可以将关键字参数传递给其他函数或方法。

  1. # 示例代码:
  2. import requests
  3. def fetch_data(url):
  4. response = requests.get(url)
  5. yield from response.json()
  6. def process_data(*data):
  7. # 处理数据的逻辑
  8. pass
  9. url = "https://api.example.com/data"
  10. data_generator = fetch_data(url)
  11. first_data, *rest_data = data_generator
  12. # 处理第一个数据
  13. process_data(first_data)
  14. # 处理剩余的数据
  15. process_data(*rest_data)

在这个例子中,我们通过fetch_data函数获取API的响应数据,并通过生成器逐个返回数据项。然后,我们使用*将第一个数据项单独处理,将剩余的数据项作为参数列表传递给process_data函数进行处理。

总结起来,*和**运算符在Python中具有广泛的应用,能够使我们的代码更加灵活和动态。它们可以用于解包序列和字典、处理可变数量的参数和关键字参数等。在实际的接口自动化工作中,我们可以利用它们来处理不确定的参数情况,提高代码的灵活性和可扩展性。

最后:下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】

软件测试面试文档

我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/30218
推荐阅读
相关标签
  

闽ICP备14008679号