元组
个人认为就像java的数组,python中的元组有以下特性:
-
任意对象的有序集合,这条没啥说的,数组的同性;
-
通过偏移读取;
-
一旦生成,不可改变;
-
固定长度,支持嵌套
默认Python元组
1)所有的多对象的,逗号分隔的,没有明确用符号定义。
>>> 1,2,3,'a'
(1, 2, 3, 'a')
2)所有函数返回的多对象
>>> def f():
return 1,2,3
>>> f()
(1, 2, 3)
单对象Python元组
>>> a=('a')
>>> type(a)
< type 'str'>
>>>
非要创建单对象元组,可以通过下面这种做法:
>>> a=('a',)
>>> type(a)
< type 'tuple'>
-
#coding:utf-8
-
#!/usr/bin/python
-
# Filename: tuple.py
-
-
mytuple=(1,2,5,6,"abc")
-
-
for i in mytuple:
-
print i
-
str=mytuple[-1]
-
print str
-
a=1
-
b=2
-
a,b=b,a
-
print "交换之前a=1,b=2 之后a=%d b=%d" %(a,b)
-
-
addressbook=(("king","qq:123444","tel:4566"),("jack","qq:123555","tel:456677"),("tom","qq:123666","tel:2224566"),
-
("peter","qq:123777","tel:45668888"))
-
-
#遍历二维数组
-
for i in xrange(len(addressbook)):
-
for j in xrange(len(addressbook[i])):
-
print addressbook[i][j],
-
print "n",
-
-
1
-
2
-
5
-
6
-
abc
-
abc
-
交换之前a=1,b=2 之后a=2 b=1
-
king qq:123444 tel:4566
-
jack qq:123555 tel:456677
-
tom qq:123666 tel:2224566
-
peter qq:123777 tel:45668888
阅读(2644) | 评论(0) | 转发(1) |