元组的常用方法


1、count(获取某个元素在元组中出现的次数)

a = (1, 2, 1, 4, 1, 6, 7)
print(a.count(1))

2、index(获取元组中某个元素的索引)

a = (1, 2, 3, 4, 5, 6)
print(a.index(6))

3、解组

nums = (1, 2, 3, 4)
num1, num2, num3, num4 = nums
print(num1, num2, num3, num4)

4、部分解组

nums = (1, 2, 3, 4)
num1, num2, _, _ = nums
print(num1, num2)

5、类型转换

a = tuple([1, 2, 3, 4])
print(a)
print(type(a))

a = tuple('abcdefg')
print(a)
print(type(a))

results matching ""

    No results matching ""