1 在Python中还有另一种叫做序列的数据类型。它和列表比较相近,只是它的元素的值是固定的。序列中的元素以逗号分隔开。
如果要创造一个包含一个元素的序列,那需要在序列的最后加上逗号。
要是不加逗号,就把这个变量当成字符串
>>> tuple = ('a','b','c','d','e')
>>> tuple
('a', 'b', 'c', 'd', 'e')
>>> t1 = ('a',)
>>> type(t1)
<type 'tuple'>
>>> t2 = ('a')
>>> type(t2)
<type 'str'>
>>>
2 序列的基本操作
>>> tuple = ('a','b','c','d','e')
>>> tuple[0]
'a'
>>> tuple [1:3]
('b', 'c')
>>> tuple = ('A',) + tuple[1:]
>>> tuple
('A', 'b', 'c', 'd', 'e')
>>>
3 序列赋值
在编程中,我们可能要交换两个变量的值。用传统的方法,需要一个
临时的中间变量。例如:
>>> temp = a
>>> a = b
>>> b = temp
Python用序列轻松的解决了这个问题:
>>> a = 1
>>> b = 2
>>> c = 3
>>> a,b,c = c,b,a
>>> print a,b,c,
3 2 1
>>>
4 序列作为函数返回值
>>> def swap(x,y):
return y,x
>>> a = 1
>>> b = 2
>>> swap(a,b)
(2, 1)
>>> print a
1
>>> print b
2
>>>
5 随机数列表
>>> def randomList(n):
>>> def randomList(n):
s = [0]*n
for i in range(n):
s[i] = random.random()
return s
>>> randomList(8)
[0.11038732464338552, 0.9543103411088475, 0.3656549066195769, 0.9624530061757608, 0.4135884626950982, 0.7189428174807532, 0.34551707284044897, 0.8007300900465738]