import random
items1 = [35, 12, 99, 68]
items2 = [45, 8, 29]
#列表的拼接
items3 = items2 + items1 #[45, 8, 29, 35, 12, 99, 68]
print(items3)
#列表的重复
items4 = ['hello'] * 3
print(items4) #['hello', 'hello', 'hello']
#列表的成员运算
print(100 in items3) #False
print('hello' in items4) #True
#获取列表的长度(元素个数)
size = len(items3)
print(size)
#列表的索引
print(items3[0], items3[-1], items3[-size])#[-size] = [0]
print(items3[size - 1], items3[-1]) #equal
#列表的切片
print(items3[: 5])#0号到4号
print(items3[4:])#4号到末尾 包含
print(items3[-5:-7:-1])#-5到-7(不包含) 步长为-1
print(items3[::-2]) #从-1开始 -2为步长
#列表的比较运算
items5 = [1, 2, 3, 4]
items6 = list(range(1, 5))
#两个列表的比较相等性比的是对应索引位置上的元素是否相等
print(items5 == items6)#True
items7 = [3, 2, 1]
# 两个列表大小的比较是对应索引位置上的元素的大小
print(items5 <= items7) #True
#列表元素的遍历
# 方法一
items = ['Python', 'Java', 'Go', 'Kotlin']
for index in range(len(items)):
print(items[index])
# 方法二
for item in items:
print(item)
counters = [0] * 6
for _ in range(6000):
face = random.randint(1, 6)
counters[face - 1] += 1
for face in range(1, 7):
print(f'{face}点出现了{counters[face - 1]}次')
#列表的方法
#添加和删除元素
# 使用append 在列表尾部添加元素
items.append('Swift')#['Python', 'Java', 'Go', 'Kotlin', 'Swift']
print(items)
#使用insert方法在列表指定索引位置插入元素
items.insert(2, 'SQL')
print(items)#['Python', 'Java', 'SQL', 'Go', 'Kotlin', 'Swift']
#删除指定的元素
items.remove('Java')#['Python', 'SQL', 'Go', 'Kotlin', 'Swift']
print(items)
#删除指定索引位置的元素
items.pop(0) #equals del items[0]
print(items)#['SQL', 'Go', 'Kotlin', 'Swift']
items.pop(len(items) - 1)
print(items)#['SQL', 'Go', 'Kotlin']
#清空列表中的元素
items.clear()
print(items)
items = ['Python', 'Java', 'Java', 'Go', 'Kotlin', 'Python']
#查找元素的索引位置
print(items.index('Python')) #0
print(items.index('Python', 2)) #5
#print(items.index('Java', 3)) #Java is not in list
#查找元素出现的次数
print(items.count('Python')) #2
print(items.count('Go')) #1
print(items.count('Swfit')) #0
#排序
items.sort()
print(items)
#反转
items.reverse()
print(items)
#列表的生成式
#创建一个由1到9的数字构成的列表
items1 = []
for x in range(1, 10):
items1.append(x)
print(items1)
#创建一个由'hello world'中除空格和原因字母外的字符构成的列表
items2 = []
for x in 'hello world':
if x not in ' aeiou':
items2.append(x)
print(items2)
#创建一个由两个字符串中字符的笛卡尔积构成的列表
items3 = []
for x in 'ABC':
for y in '12':
items3.append(x + y)
print(items3)
#通过生成式创建列表
#1 - 9
items1 = [x for x in range(1, 10)]
print(items1)
items2 = [x for x in 'hello world' if x not in ' aeiou']
print(items2)
items3 = [x + y for x in 'ABC' for y in '12']
print(items3)
#强烈建议用生成式语法来创建列表
#嵌套的列表
scores = [[0] * 3 for _ in range (5)]
print(scores)
scores[0][0] = 100
print(scores)
07-22
1960
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-11
09-18
7万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-04