Python - 在集合中追加多个元素
在这篇文章中,给出了一个集合和元素列表,任务是编写一个Python程序来一次在集合中追加多个元素。
例子:
Input : test_set = {6, 4, 2, 7, 9}, up_ele = [1, 5, 10]
Output : {1, 2, 4, 5, 6, 7, 9, 10}
Explanation : All elements are updated and reordered. (5 at 3rd position).
Input : test_set = {6, 4, 2, 7, 9}, up_ele = [1, 5, 8]
Output : {1, 2, 4, 5, 6, 7, 8, 9, 10}
Explanation : All elements are updated and reordered. (8 at 7th position).
方法#1:使用update()
在这里,我们使用内置的 update() 来使列表中的所有元素与现有集合对齐。
Python3
# Python3 code to demonstrate working of
# Append Multiple elements in set
# Using update()
# initializing set
test_set = {6, 4, 2, 7, 9}
# printing original set
print("The original set is : " + str(test_set))
# initializing adding elements
up_ele = [1, 5, 10]
# update() appends element in set
# internally reorders
test_set.update(up_ele)
# printing result
print("Set after adding elements : " + str(test_set))
Python3
# Python3 code to demonstrate working of
# Append Multiple elements in set
# Using | operator ( Pipe operator )
# initializing set
test_set = {6, 4, 2, 7, 9}
# printing original set
print("The original set is : " + str(test_set))
# initializing adding elements
up_ele = [1, 5, 10]
# | performing task of updating
test_set |= set(up_ele)
# printing result
print("Set after adding elements : " + str(test_set))
输出:
The original set is : {2, 4, 6, 7, 9}
Set after adding elements : {1, 2, 4, 5, 6, 7, 9, 10}
方法#2:使用 |运算符(管道运算符)
管道运算符在内部调用 union(),它可用于执行更新元素集的任务。
蟒蛇3
# Python3 code to demonstrate working of
# Append Multiple elements in set
# Using | operator ( Pipe operator )
# initializing set
test_set = {6, 4, 2, 7, 9}
# printing original set
print("The original set is : " + str(test_set))
# initializing adding elements
up_ele = [1, 5, 10]
# | performing task of updating
test_set |= set(up_ele)
# printing result
print("Set after adding elements : " + str(test_set))
输出:
The original set is : {2, 4, 6, 7, 9}
Set after adding elements : {1, 2, 4, 5, 6, 7, 9, 10}