Python 集合操作:定义、遍历、添加元素

① 定义集合

vegetables = {'cabbage', 'potato', 'tomato', 'cucumber'}
fruits = {'apple', 'orange', 'banana', 'tomato', 'cucumber'}

② 遍历集合

输出 fruits 所有元素:

for fruit in fruits:
    print(fruit)

输出结果:

apple
orange
banana
tomato
cucumber

③ 添加集合元素

添加 'peach' 到 fruits

fruits.add('peach')

现在 fruits 集合中包含 'peach' 元素。

Python 集合操作:定义、遍历、添加元素

原文地址: https://www.cveoy.top/t/topic/opYT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录