cfmonkey的笔记本

Python笔记9 : 数据结构

python中有三种内建的数据结构-----列表(List), 元组(Tuple), 字典(Dict)

List

example:

#!/usr/bin/python
# Filename: using_list.py
# This is my shopping list

shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'I have', len(shoplist),'items to purchase.'
print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
    print item,
print '\nI also have to buy rice.'
shoplist.append('rice')
print 'My shopping list is now', shoplist
print 'I will sort my list now'
shoplist.sort()
print 'Sorted shopping list is', shoplist
print 'The first item I will buy is', shoplist[0]
olditem = shoplist[0]
del shoplist[0]
print 'I bought the', olditem
print 'My shopping list is now', shoplist 

output:

$ python using_list.py
I have 4 items to purchase.
These items are: apple mango carrot banana
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']

  1. 可以在列表中添加任何类型的数据. 使用append()函数.
  2. List是一个可变结构, 即可以改变列表内容和长度等.
  3. 使用for...in....在列表中各项目间递归.
  4. 我们在print语句的结尾使用了一个 逗号(comma) 来消除每个print语句自动打印的换行符。
  5. 使用del删除列表项. Python从0开始计数.
  6. help(list)

Tuple

DIct

posted on 2007-07-05 15:18 cfmonkey 阅读(189) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2007年7月>
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

统计

常用链接

留言簿(2)

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜