Python 遍历集合中的元素

遍历集合中的元素

由于集合是无序的,集合中的元素没有索引,因此你不能通过引用索引来访问集合中的元素。

但是,你可以使用 for 循环遍历集合中的元素,或者使用 in 关键字询问集合中是否存在指定的值。

实例

例子 1

遍历集合,并打印值:

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

for x in thisset:
print(x)

亲自试一试

例子 2

检查集合中是否存在 "banana":

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

print("banana" in thisset)

亲自试一试