janneyabc 发表于 2017-4-27 11:22:54

菜鸟也来学python 笔记3

  
  

  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
'a'
>>> tuple
('b', 'c')
>>> tuple = ('A',) + tuple
>>> 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 = *n
for i in range(n):
s = random.random()
return s
>>> randomList(8)

 
页: [1]
查看完整版本: 菜鸟也来学python 笔记3