python学习笔记--列表list

# 列表 list [] 类似于js中的数组,下标从0开始

nameList = ['Tom', 'Kitty', 'Jack', 'Kimmy', 'Tengxi']

# 切片 左包括右不包括 用:表示
# print(nameList[1:2])
# print(nameList[1: -1]) # 从索引位置切到倒数第二个元素
# print(nameList[1:]) # 从索引位置切到最后一个
# print(nameList[1: len(nameList)]) # 从索引位置切到最后一个
# print(nameList[0:-1:2]) # 最后一个参数是步长,隔几个取一次,步长带方向
# print(nameList[3::-2]) # 从右往左取,第一个定位是第一个想要的目标的位置,方向加在步长上

# 添加元素 
# append() 添加新元素到列表最后一项
# insert(i) 有索引值 新元素的索引值是指定的索引值 
# nameList.append('Zara')
# print('new name list ', nameList)
# nameList.insert(2, 'Monki')
# print('insert name list', nameList)


# 修改元素
# nameList[2] = 'Gome'
# print(nameList)

# 修改多个元素,用切片先读取,然后按格式赋值
# nameList[1:3] = ['Kevin', 'Amy']
# print(nameList)


# 删除
# remove 列表的内置方法,可以通过.调用,删除指定内容,不返回被删除的元素
# nameList.remove(nameList[0])
# nameList.remove('Jack') # 需要判断列表中有没有要删除的元素
# print(nameList)

# clear 清空列表

# pop 可以返回被删掉的元素,根据索引删除
# b = nameList.pop(2)
# print(nameList)
# print(b)

# del 不是列表内置方法,可以删变量,可以删整个对象
# del nameList[2]
# print(nameList)


# 列表的内置方法

# count 统计指定元素在列表中出现的次数,返回值是int类型
countList = ['to', 'be', 'or', 'not', 'to', 'be']
# print(type(countList.count('yzy')))

# extend 类似于js中的数组连接 concat 无返回值
# nameList.extend(countList)
# print(nameList)

# index 找指定元素在列表中的位置,如果要找的元素在列表中多次出现,只会返回第一次出现的位置
# print(nameList.index('be'))

# 找重复出现的元素的第二个的位置
# firstIndex = countList.index('to')
# subCountList = countList[firstIndex + 1: ]
# secondIndex = subCountList.index('to')
# index = secondIndex + firstIndex + 1
# print(index)

# reverse 列表倒序 无返回值
# countList.reverse()
# print(countList)

# sort 列表排序 无返回值,文字按照ASCII码的位置排序,默认从小到大,加reverse = True 排序加倒序 从大到小了
count = [3, 5, 2, 7, 9, 1]
# count.sort(reverse = True)
# print(count)

# countList.sort(reverse = True) 
# print(countList)

# in 看元素在不在列表中
# a = 1 in count
# print(a)

猜你喜欢

转载自blog.csdn.net/tengxi_5290/article/details/88896162