您的位置:首页 > 编程语言 > Python开发

Python 元组、列表、字典、文件的用法

2014-07-05 15:15 891 查看
转自 http://yangsq.iteye.com/blog/128508

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

元组(Tuple)

笛卡尔积中每一个元素(d1,d2,…,dn)叫作一个n元组(n-tuple)或简称元组。

元组是关系数据库中的基本概念,关系是一张表,表中的每行(即数据库中的每条记录)就是一个元组,每列就是一个属性。 在二维表里,元组也称为记录。

元组是python中内置的一种数据结构

元组和列表十分类似,只不过元组和字符串一样是不可变的,即你不能修改元组。元组通过圆括号中用逗号分割的项目定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。

1、Python中元组的书面形式和规范:

tuplename=(tupleitem1,tupleitem2,tupleitem3,tupleitem4)

tuplename=tupleitem1,tupleitem2,tupleitem3,tupleitem4
注意:定义元组的是逗号,而非括号。

>>> zoo = ('wolf', 'elephant', 'penguin')
>>> print 'Number of animals in the zoo is', len(zoo)
Number of animals in the zoo is 3
>>> new_zoo = ('monkey', 'dolphin', zoo)
>>> print 'Number of animals in the new zoo is', len(new_zoo)
Number of animals in the new zoo is 3
>>> print 'All animals in new zoo are', new_zoo
All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))
>>> print 'Animals brought from old zoo are', new_zoo[2]
Animals brought from old zoo are ('wolf', 'elephant', 'penguin')
>>> print 'Last animal brought from old zoo is', new_zoo[2][2]
Last animal brought from old zoo is penguin
一个空的元组由一对空的圆括号组成,如 myempty = ()。然而,含有单个元素的元组必须在第一个(唯一一个)项目后跟一个逗号,这样Python才能区分元组和表达式中一个带圆括号的对象。

python中的元组有以下特性:

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

例子
>>> (0, 'haha', (4j, 'y'))   
(0, 'haha', (4j, 'y'))   
>>> t = (1, 3, 'b')   
>>> t[2]   
'b'   
>>> t[3]    
Traceback (most recent call last):   
  File "#41>", line 1, in <module></module>   
    t[3]   
IndexError: tuple index out of range  
>>> t[-1]   
'b'   
>>> t[0:-1]   
(1, 3)   
>>> t * 2   
(1, 3, 'b', 1, 3, 'b')   
>>> for x in t:   
    <span style="white-space:pre">	</span>print x,  
         
1 3 b   
>>> 'b' in t   
True  
>>> q = t + ((3, 'abc'))   
>>> q   
(1, 3, 'b', 3, 'abc')   
>>> for x in (2, (3, 'a')):   
    <span style="white-space:pre">	</span>print x   
        
2   
(3, 'a')   
>>> len(q)   
5   
>>> len((2, (3, 'abc')))   
2   
>>> (1, 2, 3)[1]   
2   
>>> q[1] = 'd'   
  
Traceback (most recent call last):   
  File "#57>", line 1, in <module></module>   
    q[1] = 'd'   
TypeError: 'tuple' object does not support item assignment   
>>> a = ('b', 'c', q)   
>>> 1 in a   
False  
>>> q in a   
True  
>>> a   
('b', 'c', (1, 3, 'b', 3, 'abc'))   
>>> q = 'd'
>>> q
'd'<span style="white-space:pre">	</span>   
>>> a   
('b', 'c', (1, 3, 'b', 3, 'abc'))

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

列表(List)

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

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

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

1) 首先是基本用法
>>> l = ['a', 'b', 'c']
>>> len(l)
3
>>> l + ['d']
['a', 'b', 'c', 'd']
>>> l * 2
['a', 'b', 'c', 'a', 'b', 'c']
>>> for x in l:
<span style="white-space:pre">	</span>print x,

a b c
2) 索引和分片,赋值(单个元素赋值,分片赋值)
>>> l = ['abc', 'def', 'ghi', 123]
>>> l[2]
'ghi'
>>> l[-3]
'def'
>>> l[:3]
['abc', 'def', 'ghi']
>>> l[1] = 'haha'
>>> l
['abc', 'haha', 'ghi', 123]
>>> l[1:] = ['apple', 'banana']
>>> l
['abc', 'apple', 'banana']
>>> l[2] = [123, 345, 456]
>>> l
['abc', 'apple', [123, 345, 456]]
>>> l[1:] = [123, 234, 345, 456, 567]
>>> l
['abc', 123, 234, 345, 456, 567]
3) 添加、排序、删除操作
>>> l = ['abc', 'def', 'ghi', 123]
>>> l.append(456)
>>> l
['abc', 'def', 'ghi', 123, 456]
>>> l.sort()
>>> l
[123, 456, 'abc', 'def', 'ghi']
>>> del l[0]
>>> l
[456, 'abc', 'def', 'ghi']
>>> del l[2:]
>>> l
[456, 'abc']
4)一些有趣的用法(来自论坛 id—咖啡舞者)

      去掉列表中每个元素头尾的空格:
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> [str.strip() for str in freshfruit]
['banana', 'loganberry', 'passion fruit']
把列表中,大于3的元素,乘以2:
>>> vec = [2, 4, 6]
>>> [2*x for x in vec if x > 3]
[8, 12]
把列表1的每一个元素和列表2的每一个元素相乘:
>>> lst1 = [2, 4, 6]
>>> lst2 = [4, 3, -9]
>>> [x*y for x in lst1 for y in lst2]
[8, 6, -18, 16, 12, -36, 24, 18, -54]
取获[0-10)的平方:
<<< [x**2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


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

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

 1) 基本操作
>>> 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) 修改,删除,添加
>>> 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)对字典的遍历
>>> table = {'abc':1, 'def':2, 'ghi':3}
>>> for key in table.keys():
<span style="white-space:pre">	</span>print key, '\t', table[key]

abc     1
ghi     3
def     2


文件(File)

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

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

2) 文件读
>>> myfile = open('myfile', 'r')
>>> myfile.readlinereadline()
'hello world\n'
很是简单,这样两句就顶java一长串的流嵌套,当然,java那样做也是有道理的。

ok,学了不少,说实话,python的core真的没多少,也很简单,难的是何时和如何用python。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python