列表(list) 的 详解 及 代码


本文地址: http://blog.csdn.net/caroline_wendy/article/details/17290001


列表(list)是存储项目的数据结构, 包含很多项, 使用方括号("[]")进行存储;

列表长度,len()函数;

列表末尾增加一项, append()函数;

列表排序,sort()函数;

使用下标索引, 获得或改变一个值;

使用del方法, 删除一个元素;

其他方法参见Python手册;


代码如下:

# -*- coding: utf-8 -*-  #==================== #File: abop.py #Author: Wendy #Date: 2013-12-03 #====================  #eclipse pydev, python3.3  shoplist = ['apple', 'mango', 'carrot', 'banana'] print('I have', len(shoplist), 'items to purchase') #求列表的长度 print('These items are:', end=' ') #end表示不是换行, 最后结束的是' ' for item in shoplist:     print(item, end=' ')  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) #打印剩下的列表

输出:

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']