Python 访问集合项

访问集合项

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

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

例子 1

遍历集合,并打印值:

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

for x in thisset:
  print(x)

亲自试一试

例子 2

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

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

print("banana" in thisset)

亲自试一试