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

python对列表操作

2016-05-10 10:15 1021 查看
列表跟元组一样,都是序列,但元组是不可变的,列表是可变的,它们可以被修改。因此,列表不仅可以做元组能做的事情,而且还能做元组所不能做的事情。

创建列表

和元组的区别就是,用来包装元素的是方括号而不是圆括号。

#创建一个带有一些元素的列表,然后用for循环显示出来
inventory=["sword","armor","shield","healing potion"]
print("Your items:")
for item in inventory:
print(item)



对列表,len(),in,索引,切片

inventory=["sword","armor","shield","healing potion"]
#获取列表长度
print("You have",len(inventory),"items in your possession.")
#利用in测试成员关系
if "healing potion" in inventory:
print("in inventory")
#对列表进行索引
print("inventory[1]",inventory[1])
#对列表进行切片
print("inventory[1:3]",inventory[1:3])
输出:



对列表进行连接

列表只能连接相同类型的序列(不过,貌似,字符串和数字可以混)

#连接两个列表
inventory=["sword","armor","shield","healing potion"]
chest=["gold","gems"]
inventory+=chest
print(inventory)
输出:



#连接两个列表
inventory=["sword","armor","shield","healing potion"]
chest=[1,2]
inventory+=chest
print(inventory)
输出:



列表的可变性

列表和元组的最大区别就是,列表是可变的,元组是不可变的。

通过索引对列表元素进行赋值

inventory=["sword","armor","shield","healing potion"]
inventory[0]="crossbow"
print(inventory)
输出:



注意:虽然可以利用索引机制为列表中已有的元素赋新值,但是不能用这种方式创建新元素。对不存在的元素的赋值操作都会引发一个错误。

inventory=["sword","armor","shield","healing potion"]
inventory[4]="4"
print(inventory)
输出:



通过切片对列表进行赋值

inventory=["sword","armor","shield","healing potion"]
inventory[2:4]="crossbow"
print(inventory)
输出:



inventory=["sword","armor","shield","healing potion"]
inventory[2:4]=["crossbow"]
print(inventory)
输出:



注意:赋值的时候,应该用列表进行赋值。上边把crossbow当成了一个列表,列表元素为"c","r","o","s","s","b","o","w"

删除列表元素

可以用del删除列表中的元素-只需在del后面指明待删除的元素即可。删除元素之后并不会在序列中产生一个空位。列表的长度会减一,被删除元素后面的所有元素都会“往前走”一个位置。

inventory=["sword","armor","shield","healing potion"]
del inventory[1]
print(inventory)
输出:



删除列表切片

inventory=["sword","armor","shield","healing potion"]
del inventory[0:2]
print(inventory)
输出:



append()方法

append()方法用于在列表末尾添加新的对象。

list.append(obj)

参数:obj添加到列表末尾的对象。

返回值:该方法无返回值,但是会修改原来中的列表。

aList=[123,'xyz','zarz','abc']
aList.append(2009)
print "Update List: ",aList



列表的重复操作 *

#!/usr/bin/env python
# coding=utf-8

list=["yhk","lym"]
print list
print list*4

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: