马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
学py列表时的一些总结,从网上看了一些前人的总结自己也添加补充了一些参见python列表的一些常用方法以及函数 - smelond - 博客园 (cnblogs.com)萌新千万要注意括号是()还是[] 
 
1、list.count()统计: 
 
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] 
list_count = list.count(4)  # 统计某个元素在列表中出现的次数 
 
 
2、list.append()添加对象: 
 
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] 
list.append("obj")  # 在列表末尾添加新的对象 
print(list) 
 
[6, 4, 5, 2, 744, 1, 76, 13, 8, 4, 'obj'] 
  
 
3、list.extend()扩展列表: 
 
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] 
list1 = [123, 456, 789] 
list.extend(list1)  # 扩展列表,在列表末尾一次性追加另一个列表中的多个值(相当于把list1的元素复制到了list) 
print(list) 
 
[6, 4, 5, 2, 744, 1, 76, 13, 8, 4, 123, 456, 789] 
  
 
4、list.pop()删除对象: 
 
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] 
list.pop(1)#移出列表中的一个元素,(默认最后一个元素) 
print(list) 
 
[6, 5, 2, 744, 1, 76, 13, 8, 4] 
  
 
5、list.remove()删除匹配项: 
 
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] 
list.remove(4)  # 移除列表中某个值的第一个匹配项(只会移出第一个) 
print(list) 
 
[6, 5, 2, 744, 1, 76, 13, 8, 4 
  
补充:de语句 
可以简单的删除一整个列表 
del list 1 
(此时list1就不存在了再用会报错,而不是成为空的) 
也可以删除特定的元素 
del list1[1] 
 
 
6、list.insert()插入对象: 
 
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] 
list.insert(3, "test")#将对象插入列表的第三个位置 
print(list) 
 
[6, 4, 5, 'test', 2, 744, 1, 76, 13, 8, 4] 
  
 
7、list.copy复制列表: 
 
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] 
list1 = list.copy()    # 复制一个副本,原值和新复制的变量互不影响 
print(list1) 
 
[4, 8, 13, 76, 1, 744, 2, 5, 4, 6] 
  
 
8、list.reverse()反向排序: 
 
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] 
list.reverse()  # 反向列表中元素 
print(list) 
 
[4, 8, 13, 76, 1, 744, 2, 5, 4, 6] 
  
 
9、list.index()获取索引: 
 
# 修改第一个获取到对象 
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] 
list_index = list.index(4)  # 从列表中找出某个值第一个匹配项的索引位置 
list[list_index] = 999 #将我们获取到的索引给他修改为999 
print(list) 
 
[6, 999, 5, 2, 744, 1, 76, 13, 8, 4] 
 
 
# 修改所有获取到对象 
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] 
for i in range(list.count(4)):  # 用列表的方法count找到有多少元素等于4,然后for在来循环 
    list_index = list.index(4)  # 找到的每一个4都用来赋给list_index 
    list[list_index] = 999  # 最后将最后将我们获取到的索引改为999 
    print(list)   # print我放入了for循环里面,所以输出了两条,但是从这里我们可以看到,第一次改了第一个4,第二次改了第二个4 
 
[6, 999, 5, 2, 744, 1, 76, 13, 8, 4] 
[6, 999, 5, 2, 744, 1, 76, 13, 8, 999] 
  
 
10、list.sort()排序: 
 
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] 
list.sort()#对原列表进行排序.根据ascii排序 
print(list) 
 
[1, 2, 4, 4, 5, 6, 8, 13, 76, 744] 
  
 
11、list[obj]步长: 
 
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] 
print(list[0:-1:2])  # 这个被称为步长,最后一个2代表每隔2个元素打印一次,默认就是一步 
print(list[::2])  # 这种效果和上面差不多,如果是从0开始,可以把0省略不写 
 
12、len(list): 
 
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] 
len(list)    # 返回列表元素的个数 
print(len(list)) 
 
13、max(list): 
 
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] 
print(max(list))# 返回列表元素的最大值 
 
14、min(list): 
 
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] 
print(min(list))# 返回列表元素的最小值 
 
 
 
 |