整理:列表(元组)操作常用函数

#列表声明
list0 = list()
list0 = list("abcdefg")
list0 = ["a","b","c","d","e","f"]

#列表运算符
#加法运算
list1 = [23, 22, 12]
list2 = [90, 80, 70]
new_list = list1 + list2  
#new_list = [23, 22, 12, 90, 80, 70]

#==  !=  >=  <=  >  < 将两个列表中的元素一一比较
result = list1 >= list2

#乘法运算
new_list = list1 * 3
#new_list = [23, 22, 12, 23, 22, 12, 23, 22, 12]

#获得列表的元素个数(长度)
length = len(list1)

#获得最大值
max = max(list0)

#追加元素
list0.append(33)

#在指定位置添加元素
list0.insert(1, "good")

#合并其他序列
list0.extend([23, 43, 65])

#删除指定位置元素 根据下标
list0.pop(2)
#默认删除末尾元素
list0.pop()
#删除第一次出现的元素 根据值
list0.remove("you")

#计算某个元素在列表中出现的次数
list0.count(80)

#列表逆序存放
list0.reverse()
#通过切片逆序
list0[::-1]

#列表切片
list0[start:stop:step] #左闭右开

#排序
list0.sort() #默认升序
list0.sort(key=len,reverse=True) #根据长度降序排序

'''
tuple和list类似,tuple一旦初始化就不能修改
所以没有列表中的insert()、remove()、append()等方法
'''
#元组的不变性值的是地址指向不变化
tuple0 = (12, 34, ["a", "b"])
#操作元组中的元素
#只能获取,不能直接修改元素的地址
# 0-len(tuple0)- 1     [-len(tuple0), -1]
value = tuple5[0]
print(value)

tuple0[0] = 13
print(tuple5) #TypeError: 'tuple' object does not support item assignment

#可以操作,因为下标为2的位置地址没有发生变化
tuple5[2][0] = "m"



list0 = [12, 5, 7, 0, 29, 35, 0, 0, 0, 26, 0]
#移除掉列表中所有的0元素
for item in list0:
    if item == 0:
        # remove 移除的是重复元素中第一次出现的
        list0.remove(0)
print(list0)
#结果:[12, 5, 7, 29, 35, 26, 0]
#原因:列表长度在不停的变化

while 0 in list0:
    list0.remove(0)
print(list0)
#结果:[12, 5, 7, 29, 35, 26]




猜你喜欢

转载自blog.csdn.net/Mithrandir_/article/details/81335062
今日推荐