ITeye博客

python 数据类型

8366 · 2012-12-08 22:57 · Python · 编程语言 · Markdown

Python 元组、列表、字典、文件

转自http://yangsq.iteye.com/category/20857

python的元组、列表、字典数据类型是很python(there python is a adjective )的数据结构。这些结构都是经过足够优化后的,所以如果使用好的话,在某些area会有很大的益处。

元组

         个人认为就像java的数组,python中的元组有以下特性:

  • 任意对象的有序集合,这条没啥说的,数组的同性;
  • 通过偏移读取;
  • 一旦生成,不可改变;
  • 固定长度,支持嵌套

         来例子吧:

python 代码

  1. >>> (0, 'haha', (4j, 'y'))
  2. (0, 'haha', (4j, 'y'))
  3. >>> t = (1, 3, 'b')
  4. >>> t[2]
  5. 'b'
  6. >>> t[3]
  7. Traceback (most recent call last):
  8. File "#41>", line 1, in <module></module>
  9. t[3]
  10. IndexError :  tuple   index  out of  range
  11. >>> t[-1]
  12. 'b'
  13. >>> t[0:-1]
  14. (1, 3)
  15. >>> t * 2
  16. (1, 3, 'b', 1, 3, 'b')
  17. >>>  for  x  in  t:
  18. print  x,
  19. 1 3 b
  20. >>> 'b'  in  t
  21. True
  22. >>> q = t + ((3, 'abc'))
  23. >>> q
  24. (1, 3, 'b', 3, 'abc')
  25. >>>  for  x  in  (2, (3, 'a')):
  26. print  x
  27. 2
  28. (3, 'a')
  29. >>>  len (q)
  30. 5
  31. >>>  len ((2, (3, 'abc')))
  32. 2
  33. >>> (1, 2, 3)[1]
  34. 2
  35. >>> q[1] = 'd'
  36. Traceback (most recent call last):
  37. File "#57>", line 1, in <module></module>
  38. q[1] = 'd'
  39. TypeError : ' tuple '  object  does  not  support item assignment
  40. >>> a = ('b', 'c', q)
  41. >>> 1  in  a
  42. False
  43. >>> q  in  a
  44. True
  45. >>> a
  46. ('b', 'c', (1, 3, 'b', 3, 'abc'))
  47. >>> q='d'
  48. >>> a
  49. ('b', 'c', (1, 3, 'b', 3, 'abc'))

上面的例子足以说明大部分了,使用元组时最重要的一点是“一旦生成,就不可变了”。

列表

      列表就像java里的collection,所具有的特性也要比元组更多,更灵活,其character总结如下:

  • 任意对象的有序集合;
  • 可通过偏移存取,注意,列表中的元素都是可变的,这是不同于元组的;
  • 长度可变,支持嵌套;
  • 还有一些类似java的对象引用机制

      由于列表的这些特性,使得列表在实际应用中被广泛使用,下面是一些例子。

1) 首先是基本用法

python 代码

  1. >>> l = ['a', 'b', 'c']
  2. >>>  len (l)
  3. 3
  4. >>> l + ['d']
  5. ['a', 'b', 'c', 'd']
  6. >>> l * 2
  7. ['a', 'b', 'c', 'a', 'b', 'c']
  8. >>>  for  x  in  l:
  9. print  x,
  10. a b c

2) 索引和分片,赋值(单个元素赋值,分片赋值)

python 代码

  1. >>> l = ['abc', ' def ', 'ghi', 123]
  2. >>> l[2]
  3. 'ghi'
  4. >>> l[-3]
  5. ' def '
  6. >>> l[:3]
  7. ['abc', ' def ', 'ghi']
  8. >>> l[1] = 'haha'
  9. >>> l
  10. ['abc', 'haha', 'ghi', 123]
  11. >>> l[1:] = ['apple', 'banana']
  12. >>> l
  13. ['abc', 'apple', 'banana']
  14. >>> l[2] = [123, 345, 456]
  15. >>> l
  16. ['abc', 'apple', [123, 345, 456]]
  17. >>> l[1:] = [123, 234, 345, 456, 567]
  18. >>> l
  19. ['abc', 123, 234, 345, 456, 567]

 

3) 添加、排序、删除操作

python 代码

  1. >>> l = ['abc', ' def ', 'ghi', 123]
  2. >>> l. append (456)
  3. >>> l
  4. ['abc', ' def ', 'ghi', 123, 456]
  5. >>> l.sort()
  6. >>> l
  7. [123, 456, 'abc', ' def ', 'ghi']
  8. >>>  del  l[0]
  9. >>> l
  10. [456, 'abc', ' def ', 'ghi']
  11. >>>  del  l[2:]
  12. >>> l
  13. [456, 'abc']

4)一些有趣的用法(来自论坛 id—咖啡舞者 )

      去掉列表中每个元素头尾的空格:

python 代码

  1. >>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
  2. >>> [ str .strip()  for   str   in  freshfruit]
  3. ['banana', 'loganberry', 'passion fruit']

    把列表中,大于3的元素,乘以2:

python 代码

  1. >>> vec = [2, 4, 6]
  2. >>> [2*x  for  x  in  vec  if  x > 3]
  3. [8, 12]

    把列表1的每一个元素和列表2的每一个元素相乘:

python 代码

  1. >>> lst1 = [2, 4, 6]
  2. >>> lst2 = [4, 3, -9]
  3. >>> [x*y  for  x  in  lst1  for  y  in  lst2]
  4. [8, 6, -18, 16, 12, -36, 24, 18, -54]

    取获[0-10)的平方:

python 代码

[x**2  for  x  in   range (10)]  

字典

         python里的字典就像java里的HashMap,以键值对的方式存在并操作,其特点如下

通过键来存取,而非偏移量; 键值对是无序的; 键和值可以是任意对象; 长度可变,任意嵌套; 在字典里,不能再有序列操作,虽然字典在某些方面与列表类似,但不要把列表套在字典上

 1) 基本操作

python 代码

>>> table = {'abc':1, ' def ':2, 'ghi':3}    >>> table['abc']    1    >>>  len (table)    3    >>> table. keys ()    ['abc', 'ghi', ' def ']    >>> table. values ()    [1, 3, 2]    >>> table. has_key (' def ')    True    >>> table. items ()    [('abc', 1), ('ghi', 3), (' def ', 2)]  

2) 修改,删除,添加

python 代码

>>> table = {'abc':1, ' def ':2, 'ghi':3}    >>> table['ghi'] = ('g', 'h', 'i')    >>> table    {'abc': 1, 'ghi': ('g', 'h', 'i'), ' def ': 2}    >>>  del  table['abc']    >>> table    {'ghi': ('g', 'h', 'i'), ' def ': 2}    >>> table['xyz'] = ['x', 'y', 'z']    >>> table    {'xyz': ['x', 'y', 'z'], 'ghi': ('g', 'h', 'i'), ' def ': 2}  

在这里需要来一句,对于字典的扩充,只需定义一个新的键值对即可,而对于列表,就只能用append方法或分片赋值。

3)对字典的遍历

python 代码

>>> table = {'abc':1, ' def ':2, 'ghi':3}    >>>  for  key  in  table. keys ():         print  key, '\t', table[key]               abc     1    ghi     3    def      2  

文件

与java的File类相比,python的文件类要狭义一些

1) 文件写

python 代码

>>> myfile =  open ('myfile', 'w')    >>> myfile. write ('hello world\n')    >>> myfile. close ()  

python的一个open语句就打开了一个文件(当给定的文件不存在时,会自动建立一个新的文件)。open的第一个参数是文件名,第二个参数是 操作模式,所谓操作模式就是你打开一个文件是用来干什么的,是读,还是写(当然操作模式不仅只有读和写)。还有一件事,操作完要记得关。

2) 文件读

python 代码

>>> myfile =  open ('myfile', 'r')    >>> myfile. readline readline ()    'hello world\n'  

很是简单,这样两句就顶java一长串的流嵌套,当然,java那样做也是有道理的。

ok,学了不少,说实话,python的core真的没多少,也很简单,难的是何时和如何用python

 

 

------------

字典的遍历:

 

#!/usr/bin/python
dict={"a":"apple","b":"banana","o":"orange"}
print "##########dict######################"
for i in dict:
    print "dict[%s]=" % i,dict[i]
print "###########items#####################"
for (k,v) in  dict.items():
    print "dict[%s]=" % k,v
print "###########iteritems#################"
for k,v in dict.iteritems():
    print "dict[%s]=" % k,v
print "###########iterkeys,itervalues#######"
for k,v in zip(dict.iterkeys(),dict.itervalues()):
    print "dict[%s]=" % k,v
~

 

注意:

1. 元组是()    元素固定

2. 字典是{}   添加元素用 aa['xx']=yyy

3. 列表是[]     添加元素用append

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。