个性化阅读
专注于IT技术分析

Python集合update()函数用法示例

点击下载

update()是集合中的函数:用于将集合中的元素(作为参数传递)添加到集合中。

语法:set1.update(set2)这里set1是将在其中添加set2的集合。
参数:Update()方法仅接受一个参数。单个参数可以是集合, 列表, 元组或字典。它会自动转换为集合并添加到集合中。返回值:此方法将set2添加到set1且不返回任何内容。

代码1:

# 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}

代码2:

# 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'}

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


赞(0)
未经允许不得转载:srcmini » Python集合update()函数用法示例

评论 抢沙发

评论前必须登录!