Python - 添加集合项
添加集合项
集合创建后,您无法更改其中的项目,但可以添加新项目。
要向集合中添加项目,请使用 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)
亲自试一试 »

