Python - 添加集合项
Add Items
集合一旦创建,您不能更改其项,但可以添加新项。
要向集合添加一个项,请使用 add()
方法。
示例
使用 add()
方法向集合添加一个项
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
自己动手试一试 »
添加集合
要将另一个集合中的项添加到当前集合,请使用 update()
方法。
示例
将 tropical
中的元素添加到 thisset
中
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
自己动手试一试 »
添加任何可迭代对象
update()
方法中的对象不必是集合,它可以是任何可迭代对象(元组、列表、字典等)。
示例
将列表元素添加到集合中
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)
自己动手试一试 »