接上一篇 列表 :
代码+结果:
mylist1 = ["a","b","c","a","b"]
print(mylist1.index("a",1,4)) #可以查找指定下标范围的元素,并返回找到对应数据的下标
#print(mylist1.index("a",1,3)) #范围区间,左闭右开 【1,3),找不到会报错
print(mylist1.count("b")) #统计某个元素出现几次
#排序和反转
a = [1,4,2,3]
print(a)
a.reverse() #将列表所有元素反转
print(a)
a.sort() #升序
print(a)
a.sort(reverse=True) #降序
print(a)
schoolNames = [[],[],[]] #有三个元素的空列表,每个元素都是一个空列表
schoolName = [["北京大学,”清华大学"],["南开大学","天津大学","天津师范大学"],["山东大学","中国海洋大学"]]
print(schoolName[0])
#小例子:办公室分配问题
import random
offices = [[],[],[]]
names = ["A","B","C","D","E","F","G","H"]
for name in names:
index = random.randint(0,2)
offices[index].append(name)
i = 1
for office in offices:
print("办公室%d的人数为:%d"%(i,len(office)))
i += 1
for name in office:
print("%s"%name,end="\t")
print("\n")
print("-"*20)
3
2
[1, 4, 2, 3]
[3, 2, 4, 1]
[1, 2, 3, 4]
[4, 3, 2, 1]
['北京大学,”清华大学']
办公室1的人数为:1
E
--------------------
办公室2的人数为:2
D H
--------------------
办公室3的人数为:5
A B C F G
--------------------
Process finished with exit code 0
|