# 法一# a = [1, 2, 3, 4, 5, 6]# a.reverse()# print("反转后为:", a)# 法二# a = a[::-1]# 法三# a = a[-1::-1]# 法四# a = a[len(a)-1::-1]# print("反转后为:", a)# 习题二# 获取列表中相同的元素# list1 = [11, 22, 33]# list2 = [22, 33, 44]# common = []# for i in list1:# print(i)# if i in list2:# common += [i]# print(common)
题二
现在有8位老师,3个办公室,要求将8位老师随机的分配到三个办公室中
# 八位老师分别用1-8表示import random
list1 =list(range(1,9))whileTrue:
a = random.randint(1,7)
b = random.randint(1,7)if a < b:
c = list1[0:a]
d = list1[a:b]
e = list1[b::]print(c, d, e)break
运行结果
D:\python3.6.5\python.exe D:/pycharm2019/19project/列表操作题.py
[1][2,3,4,5][6,7,8]
Process finished with exit code 0
题三
质数的判断
# 获取用户输入的任意数,判断其是否是质数# 用户输入数字
num =int(input("请输入一个数字: "))# 质数大于 1if num >1:for i inrange(2, num):if(num % i)==0:print(num,"不是质数")breakelse:print(num,"是质数")# 如果输入的数字小于或等于 1,不是质数else:print(num,"不是质数")
题四
玩家和用户石头剪刀布
# 猜拳游戏import random
a ="石头"
b ="剪刀"
c ="布"print("a表示石头","b代表剪刀","c代表布")
d =input("请输入a b c 中任意一字母代表出拳:")
e = random.choice([a, b, c])if e is d:print("平手")elif e == a and d == b or e == b and d == c or e == c and d == a:print("电脑赢")else:print("玩家赢")