python 数据类型---列表使用之三
1. 判断列表中是否存在一个元素: "in" 的使用
list = ['Frank', 99, 'is',78, 7,3,4,'smart'] print(99 in list) print(9 in list) #运行结果 True False
2. 元素个数统计: count
>>> name = ['3',4,45,4343,34,56,6,7,5,3,9] >>> name.count(9) 1 >>> name.count(3) 1 >>>
3.元素位置索引: index(
L.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.)
list = ['Frank', 99, 'is',78, 7,3,4,'smart',9,939,84,83,9] print(99 in list) print(9 in list) #count 使用 num_of_ele = list.count(9) #index 使用 posistion_of_ele = list.index(9) print("[%s] 9 in list , posistion is [%s]" %(num_of_ele, posistion_of_ele)) #测试结果 True True [2] 9 in list , posistion is [8]
4. 列表的扩展 : extend
name = ["frank", "Malon","Lee"] name2 = ["Andy", "Troy"] name.extend(name2) print(name) print(name2) #运行结果 ['frank', 'Malon', 'Lee', 'Andy', 'Troy'] ['Andy', 'Troy']
5. 列表的拷贝:copy # L.copy() -> list -- a shallow copy of L 只进行肤浅的拷贝
name = ['alex','Rain','Erik',['a','b','c'],'Frank'] name3 = name.copy() print("测试一") print(name) print(name3) print("测试二") name[0] = 'ALEX' print(name) print(name3) print("测试三") name[3][0] = 'AAAAAA' print(name) print(name3) print("测试四") name3[3][2] = 'CCCCCC' print(name) print(name3) #测试结果 测试一 ['alex', 'Rain', 'Erik', ['a', 'b', 'c'], 'Frank'] ['alex', 'Rain', 'Erik', ['a', 'b', 'c'], 'Frank'] 测试二 ['ALEX', 'Rain', 'Erik', ['a', 'b', 'c'], 'Frank'] ['alex', 'Rain', 'Erik', ['a', 'b', 'c'], 'Frank'] 测试三 ['ALEX', 'Rain', 'Erik', ['AAAAAA', 'b', 'c'], 'Frank'] ['alex', 'Rain', 'Erik', ['AAAAAA', 'b', 'c'], 'Frank'] 测试四 ['ALEX', 'Rain', 'Erik', ['AAAAAA', 'b', 'CCCCCC'], 'Frank'] ['alex', 'Rain', 'Erik', ['AAAAAA', 'b', 'CCCCCC'], 'Frank']
6. 列表copy---deepcopy (import copy)
import copy name = ['alex','Rain','Erik',['a','b','c'],'Frank'] name3 = name.copy() name4 = copy.deepcopy(name) print("测试一") print(name) print(name3) print(name4) name[3][1] = 'AAAAAAAA' print("测试二") print(name) print(name3) print(name4) #测试结果 测试一 ['alex', 'Rain', 'Erik', ['a', 'b', 'c'], 'Frank'] ['alex', 'Rain', 'Erik', ['a', 'b', 'c'], 'Frank'] ['alex', 'Rain', 'Erik', ['a', 'b', 'c'], 'Frank'] 测试二 ['alex', 'Rain', 'Erik', ['a', 'AAAAAAAA', 'c'], 'Frank'] ['alex', 'Rain', 'Erik', ['a', 'AAAAAAAA', 'c'], 'Frank'] ['alex', 'Rain', 'Erik', ['a', 'b', 'c'], 'Frank']