元组

元组的实例:

 

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 ExpressionResultsDescription
len((1, 2, 3))3Length
(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)TrueMembership
for x in (1, 2, 3): print x,1 2 3Iteration

 

L =('spam','Spam','SPAM!')

 

Python ExpressionResultsDescription
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:

SNFunction 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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值