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

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

2012-06-07 20:28 555 查看
python的元组、列表、字典数据类型是很python(there python is a adjective)的数据结构。这些结构都是经过足够优化后的,所以如果使用好的话,在某些area会有很大的益处。
元组
个人认为就像java的数组,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:
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')):
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'
>>> a
('b', 'c', (1, 3, 'b', 3, 'abc'))

上面的例子足以说明大部分了,使用元组时最重要的一点是“一旦生成,就不可变了”。
列表
列表就像java里的collection,所具有的特性也要比元组更多,更灵活,其character总结如下:

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

由于列表的这些特性,使得列表在实际应用中被广泛使用,下面是一些例子。
1) 首先是基本用法
python 代码

>>> 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:
print x,
a b c

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

>>> 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) 添加、排序、删除操作
python 代码

>>> 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—咖啡舞者)
去掉列表中每个元素头尾的空格:
python 代码

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

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

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

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

>>> 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)的平方:
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.readlinereadline()
'hello world\n'

很是简单,这样两句就顶java一长串的流嵌套,当然,java那样做也是有道理的。
ok,学了不少,说实话,python的core真的没多少,也很简单,难的是何时和如何用python。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: