Python 集合 update()

Python 集合的 update() 方法更新集合,从其他可迭代对象中添加项目。

示例

A = {'a', 'b'}
B = {1, 2, 3}

# updates A after the items of B is added to A A.update(B)
print(A) # Output: {'a', 1, 2, 'b', 3}

update() 语法

update() 方法的语法是

A.update(B)

这里,A 是一个集合,B 可以是任何可迭代对象,例如列表、集合、字典字符串等。


update() 参数

update() 方法可以接受任意数量的参数。例如,

A.update(B, C, D)

这里,

  • B, C, D - 其项目添加到集合 A 的可迭代对象

update() 返回值

update() 方法不返回任何值。


示例 1:Python 集合 update()

A = {1, 3, 5}
B = {2, 4, 6}
C = {0}

print('Original A:', A)

# adds items of B and C to A and updates A A.update(B, C)
print('A after update()', A)

输出

Original A: {1, 3, 5}
A after update() {0, 1, 2, 3, 4, 5, 6}

在上面的示例中,我们使用 update() 方法将集合 BC 的项目添加到 A 中,并使用结果集合更新 A

这里,最初集合 A 只有 3 个项目。当我们调用 update() 时,BC 的项目将添加到集合 A 中。


示例 2:update() 添加字符串和字典到集合

# string
alphabet = 'odd'

# sets
number1 = {1, 3}
number2 = {2, 4}

# add elements of the string to the set number1.update(alphabet)
print('Set and strings:', number1) # dictionary key_value = {'key': 1, 'lock' : 2}
# add keys of dictionary to the set number2.update(key_value)
print('Set and dictionary keys:', number2)

输出

Set and strings: {1, 3, 'o', 'd'}
Set and dictionary keys: {'lock', 2, 4, 'key'}

在上面的示例中,我们使用 update() 方法将字符串和字典添加到集合中。

该方法将字符串分解为单个字符,并将它们添加到集合 number1 中。同样,它将字典的键添加到集合 number2 中。

注意:如果将字典传递给 update() 方法,则字典的键将添加到集合中。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战