码迷,mamicode.com
首页 > 其他好文 > 详细

直播3-列表-字典-集合

时间:2021-01-11 10:41:13      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:老师   and   习题   div   col   each   end   编写   rgba   

# 随机分配老师到办公室
import random

teachers = [a, b, c, d, e]
offices = [[], [], []]
for name in teachers:
    num = random.randint(0, 2)
    offices[num].append(name)

# 验证是否成功
i = 1
for o in offices:
    print(f办公室{i}人数是{len(o)},老师分别是:, end= )
    for name in o:
        print(name, end=    )
    print()
    i += 1
# 不能让办公室为o,让i为办公室不严谨,最后都为4了。但思想很好,能省一个就省一个。

# 练习题1:有一个list1 = [1,2,3,4,3],请完成去重复的功能,并且最后依然是列表。
list1 = [1, 2, 3, 4, 3]
# 方法1.
print(list(set(list1)))
# 方法2.
list2 = []
for i in list1:
    if i not in list2:
        list2.append(i)
print(list2)

# 练习题2:小明一共有8000块钱,编写代码, 判断小明能不能买下购物车中所有商品?如果能,请输出“能”,否则输出“不能”。
product = [
    {"name": "电脑", "price": 7000},
    {"name": "鼠标", "price": 30},
    {"name": "usb电动小风扇", "price": 1020},
    {"name": "遮阳伞", "price": 50}]
i = 0
sum = 0
for i in product:
    sum += i["price"]
if sum < 8000:
    print("ok")
else:
    print("不能")

# 练习题3:找出同名同姓的学员, 并计算出相同姓名的个数
str1 = 哈哈, 小刘, da, da ,fe ,rere, yrte, or,weqw, dfsa
name_list = str1.split(",")
# 列表、集合方法实现
set1 = set()
for i in name_list:
    if name_list.count(i) > 1:
        set1.add(i)
for name in set1:
    print(name, name_list.count(name))

# 字典方法实现1
new_list = list(name_list)
dict1 = {}
for i in new_list:
    if new_list.count(i) > 1:
        dict1[i] = new_list.count(i)
print(dict1)

# 字典方法实现2
name_dict = {}
for name in name_list:
    if name not in name_dict:
        name_dict[name] = 1
    else:
        name_dict[name] += 1
for key, value in name_dict.items():
    if value > 1:
        print(key, value)

 

直播3-列表-字典-集合

标签:老师   and   习题   div   col   each   end   编写   rgba   

原文地址:https://www.cnblogs.com/teark/p/14247950.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!