您的位置:首页 > 理论基础 > 数据结构算法

Python数据结构之——list

2009-09-25 22:20 501 查看
Python中有四种内建的数据结构:List,Tuple,Dictionary,Set。本文主要介绍List。

List是用来存放一组对象序列。可以像list中添加元素、删除元素,同时也可以像访问数组一样访问list。List是可变的数据类型。

下面,给出一组list的使用实例:

shoplist = ['rice','apple','banana','mango']
print('I hava ',len(shoplist),' items to purchase')
print('These items are:',end=' ')
for item in shoplist:
print(item,end=' ')
print('/nI also have to buy carrot')
shoplist.append('carrot')
print('My shoplist now is: ',shoplist)
shoplist.sort()
print('My shoplist after sorted is: ',shoplist)
del shoplist[1]
print('My shoplist after del is: ',shoplist)
shoplist.reverse()
print('My shoplist after reversed is: ',shoplist)
shoplist.remove('rice')
print('My shoplist after remove is: ',shoplist)


首先,可以使用“[]”来创建一个list,并可以直接对其进行初始化;可以使用for..in语法来迭代访问list;可以使用append方法来向list中添加元素;可以使用remove方法从list中移除元素;可以使用del来从list中删除指定索引的元素;可以使用sort方法来对list进行正序的排序,在这里,需要注意的是该方法不返回值,而是直接改变list本身;可以使用reverse方法来倒置list中的元素。

关于list的进一步使用,可以使用help(list)来查看。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: