元组:
元组是一种序列,就像列表一样。元组和列表之间的区别在于,与列表(可变)不同,元组不能更改(不可变)。 元组使用括号,而列表使用方括号。
优点:运行时间快!
初始化一个元组
空元组:emptyTuple = ()
多元组:
# way 1
z = (3, 7, 4, 2)
# way 2 (tuples can also can be created without parenthesis)
z = 3, 7, 4, 2
单元组:
重要的是要记住,如果要创建仅包含一个值的元组,则需要在项目后面添加一个逗号。
# tuple with one value
tup1 = ('Michael',)
# tuple with one value
tup2 = 'Michael',
# This is a string, NOT a tuple.
notTuple = ('Michael')
访问元组内的值 :与列表雷同
# Initialize a tuple
z = (3, 7, 4, 2)
# Access the first item of a tuple at index 0
print(z[0])
print(z[-1])
#输出:
3
2
切分元组 :与列表雷同
# Initialize a tuple
z = (3, 7, 4, 2)
# first index is inclusive (before the :) and last (after the :) is not.
print(z[0:2])
print(z[:3])
print(z[-4:-1])
#输出:
(3, 7)
(3, 7, 4)
(3, 7, 4)
即使元组是不可变的,也可以采用现有元组的一部分来创建新的元组,如下例所示。
# Initialize tuple
tup1 = ('Python', 'SQL')
# Initialize another Tuple
tup2 = ('R',)
# Create new tuple based on existing tuples
new_tuple = tup1 + tup2;
print(new_tuple)
#输出:
('Python', 'SQL', 'R')
元组内部索引和元组数计数
# Initialize a tuple
animals = ('lama', 'sheep', 'lama', 48)
print(animals.index('lama'))
print(animals.count('lama'))
#输出:
0
2
遍历:
for item in animals:
for item in animals:
print(item)
#输出:
lama
sheep
lama
48
元组拆包 :数字序列
x, y = (7, 10);
print("Value of x is {}, the value of y is {}.".format(x, y))
#输出:
Value of x is 7, the value of y is 10.
枚举(enumerate):
friends = ('Steve', 'Rachel', 'Michael', 'Monica')
for index, frien in enumerate(friends):
print(index,frien)
#输出:
0 Steve
1 Rachel
2 Michael
3 Monica
元组可以用作字典键
而列表不可以作为字典键
bigramsTupleDict = {('this', 'is'): 23,
('is', 'a'): 12,
('a', 'sentence'): 2}
print(bigramsTupleDict)
#输出:
{('is', 'a'): 12, ('this', 'is'): 23, ('a', 'sentence'): 2}