Python Set | update()
2022/7/30 14:22:49
本文主要是介绍Python Set | update(),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Python update() function in set adds elements from a set (passed as an argument) to the set.
Syntax : set1.update(set2)
Here set1 is the set in which set2 will be added. Parameters : Update() method takes only a single argument. The single argument can be a set, list, tuples or a dictionary. It automatically converts into a set and adds to the set. Return value : This method adds set2 to set1 and returns nothing.
Example of Python set update()
Example 1: Working with Python set update list
# Python program to demonstrate the # use of update() method list1 = [1, 2, 3] list2 = [5, 6, 7] list3 = [10, 11, 12] # Lists converted to sets set1 = set(list2) set2 = set(list1) # Update method set1.update(set2) # Print the updated set print(set1) # List is passed as an parameter which # gets automatically converted to a set set1.update(list3) print(set1)
输出:
{1, 2, 3, 5, 6, 7} {1, 2, 3, 5, 6, 7, 10, 11, 12}
Example 2: Python set update element in set
# Python program to demonstrate the # use of update() method list1 = [1, 2, 3, 4] list2 = [1, 4, 2, 3, 5] alphabet_set = {'a', 'b', 'c'} # lists converted to sets set1 = set(list2) set2 = set(list1) # Update method set1.update(set2) # Print the updated set print(set1) set1.update(alphabet_set) print(set1)
输出:
{1, 2, 3, 4, 5} {1, 2, 3, 4, 5, 'c', 'b', 'a'}
Example 3: Add elements of the dictionary to Set
number = {1, 2, 3, 4, 5} num_Dict = {6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten'} number.update(num_Dict) print("Updated set: ", number)
输出:
Updated set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
转载:https://www.geeksforgeeks.org/python-set-update/
这篇关于Python Set | update()的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-16`PyMuPDF4LLM`:提取PDF数据的神器
- 2024-11-16四种数据科学Web界面框架快速对比:Rio、Reflex、Streamlit和Plotly Dash
- 2024-11-14获取参数学习:Python编程入门教程
- 2024-11-14Python编程基础入门
- 2024-11-14Python编程入门指南
- 2024-11-13Python基础教程
- 2024-11-12Python编程基础指南
- 2024-11-12Python基础编程教程
- 2024-11-08Python编程基础与实践示例
- 2024-11-07Python编程基础指南