元组的实例:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
创建一个空元组:
tup1 = ();
创建只有一个元素的元组:
tup1 = (50,);
访问元组的值:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0]
print "tup2[1:5]: ", tup2[1:5]
#result
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
更新元组:
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;
#result
(12, 34.56, 'abc', 'xyz')
元组的基本操作:
Python Expression | Results | Description |
---|---|---|
len((1, 2, 3)) | 3 | Length |
(1, 2, 3) + (4, 5, 6) | (1, 2, 3, 4, 5, 6) | Concatenation |
['Hi!'] * 4 | ('Hi!', 'Hi!', 'Hi!', 'Hi!') | Repetition |
3 in (1, 2, 3) | True | Membership |
for x in (1, 2, 3): print x, | 1 2 3 | Iteration |
L =('spam','Spam','SPAM!')
Python Expression | Results | Description |
---|---|---|
L[2] | 'SPAM!' | Offsets start at zero |
L[-2] | 'Spam' | Negative: count from the right |
L[1:] | ['Spam', 'SPAM!'] | Slicing fetches sections |
没有括号的元组:
print 'abc', -4.24e93, 18+6.6j, 'xyz';
x, y = 1, 2;
print "Value of x , y : ", x,y;
#result
abc -4.24e+93 (18+6.6j) xyz
Value of x , y : 1 2
元组与列表的不同是,元组是不可变的,列表是可变的
元组包含的方法:
Python includes the following tuple functions:
SN | Function with Description |
---|---|
1 | cmp(tuple1, tuple2) Compares elements of both tuples. |
2 | len(tuple) Gives the total length of the tuple. |
3 | max(tuple) Returns item from the tuple with max value. |
4 | min(tuple) Returns item from the tuple with min value. |
5 | tuple(seq) Converts a list into tuple. |