» Python快速入门 » 2. 集合篇 » 2.4 元组

元组

构建元组

a = ('a', 'b', 'c')

# from a list or any other iterable collection
c = tuple([1, 3, 5]) # (1, 3, 5)

遍历元素

a = ("fig", "mango", "watermelon")
for e in a:
    print(e)

解构元组

a = ("fig", "mango", "watermelon")
item1, item2, item3 = a
print(item1) # fig
print(item2) # mango
print(item3) # watermelon

检查元素是否存在

a = ("fig", "mango", "watermelon")
print("fig" in a) # True
print("cherry" in a) # False

元组常用方法

count 计数

a = ("fig", "mango", "fig", "watermelon", "fig")
print(a.count("fig")) # 3

index 索引

a = ("fig", "mango", "fig", "watermelon", "fig")
print(a.index("watermelon")) # 3

代码挑战

修改编辑器中代码,构建如右元组: (1, 'hello', ['a', 'b'], {'a': 1, 'b': 2}, False, (1, 2, 3))

Loading...
> 此处输出代码运行结果
上页
下页