首页 > 解决方案 > 在集合中添加项目(Python)

问题描述

我刚开始学习在集合中添加项目(Python),但后来我不明白为什么会发生这种情况

thisset = {"apple", "banana", "cherry"}

thisset.update("durian", "mango", "orange")

print(thisset)

我得到这样的输出:

{'i', 'o', 'r', 'm', 'cherry', 'n', 'u', 'a', 'apple', 'banana', 'd', 'e', 'g'}

我想要的是将其他 3 个项目放入集合中,我还需要添加/更改什么?

标签: pythonset

解决方案


根据参考,set.update(*others)将更新集合,添加所有其他元素,它所做的是set |= other | .... 所以在你的情况下,什么thisset.update("durian", "mango", "orange")thisset |= set("marian") | set("mango") | set("orange"). 为了完成你想要的,你需要传递一个列表或一组,比如thisset.update(["durian", "mango", "orange"])or thisset.update({"durian", "mango", "orange"})


推荐阅读