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