1、餐厅下午茶 (列表与元组 crr66)
某餐厅推出了优惠下午茶套餐活动。顾客可以以优惠的价格从给定的糕点和给定的饮
料中各选一款组成套餐。已知,指定的糕点包括松饼(Muffins)、提拉米苏(Tiramisu)、芝士蛋
糕(Cheese Cake)和三明治(Sandwich);指定的饮料包括红茶(Black tea,)、咖啡(Coffee)和橙汁
(Orange Juice)。请问,可以搭配出哪些套餐供客户选择?请依次打印输出各种套餐。
python
menu = ['Muffins', 'Tiramisu', 'Cheese Cake', 'Sandwich']
drinks = ['Black tea', 'Coffee', 'Orange Juice']
#遍历所有的组合
for cake in menu:
for drink in drinks:
print(f"{cake}+{drink}")
Muffins+Black tea
Muffins+Coffee
Muffins+Orange Juice
Tiramisu+Black tea
Tiramisu+Coffee
Tiramisu+Orange Juice
Cheese Cake+Black tea
Cheese Cake+Coffee
Cheese Cake+Orange Juice
Sandwich+Black tea
Sandwich+Coffee
Sandwich+Orange Juice
2、生成 1000 个 0~100 之间的随机整数,采用集合统计每个元素的出现次数
python
import random
from collections import Counter
number=[random.randint(0,100) for x in range(1000)]
print(Counter(number))
Counter({58: 19, 71: 19, 37: 18, 41: 17, 25: 17, 62: 16, 49: 16, 43: 15, 54: 15, 8: 14, 55: 14, 97: 14, 15: 14, 9: 13, 50: 13, 42: 13, 46: 13, 45: 13, 100: 13, 84: 13, 2: 12, 70: 12, 74: 12, 47: 12, 27: 12, 60: 12, 73: 12, 53: 12, 96: 11, 12: 11, 83: 11, 95: 11, 24: 11, 65: 11, 99: 11, 56: 10, 77: 10, 10: 10, 63: 10, 14: 10, 19: 10, 13: 10, 52: 10, 18: 10, 66: 10, 44: 10, 31: 10, 57: 10, 20: 9, 16: 9, 21: 9, 11: 9, 30: 9, 22: 9, 29: 9, 75: 9, 39: 9, 34: 9, 36: 9, 5: 9, 26: 9, 81: 9, 33: 9, 32: 9, 89: 9, 67: 8, 86: 8, 48: 8, 68: 8, 94: 8, 82: 8, 23: 8, 35: 8, 7: 8, 72: 8, 17: 8, 64: 8, 3: 8, 1: 8, 69: 8, 28: 7, 79: 7, 78: 7, 90: 7, 85: 7, 88: 7, 92: 7, 0: 7, 6: 7, 87: 7, 76: 6, 80: 6, 38: 6, 91: 6, 40: 6, 98: 5, 4: 5, 93: 5, 51: 4, 59: 3, 61: 3})
3、输入两个分别包含若干整数的列表 lstA 和 lstB,输出一个字典,要求使用列表 lstA 中的元素作为键,列表 lstB 中元素作为值,并且最终字典中的元素数量取决于 lstA 和 lstB 中元素最少的列表的数量。
python
def create_dict(lista,listb):
return dict(zip(lista,listb))
lista=[1,2,3,4,5]
listb=['a','b','c','d','e']
print(create_dict(lista,listb))
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
4、输入一个字符串,输出其中出现次数最多的字符及其出现的次数。要求使用字典完成。
python
def find_most_frequent_char(s):
# 创建一个空字典来存储字符及其出现的次数
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
# 找到出现次数最多的字符及其出现的次数
max_count = 0
max_char = ''
for char, count in char_count.items():
if count > max_count:
max_count = count
max_char = char
return max_char, max_count
# 测试代码
s = "hello world"
print(find_most_frequent_char(s))
('l', 3)
5、籍贯分布(字典的整体操作 crr92)
python
dicGirls = {'Jiangsu': 3, 'Zhejiang': 2, 'Jilin': 1}
dicBoys = {'Jiangsu': 8, 'Zhejiang': 5, 'Shandong': 5, 'Anhui': 4, 'Fujian': 2}
# 合并两人的调研结果
merged_dict = dicGirls.copy()
for key, value in dicBoys.items():
if key in merged_dict:
merged_dict[key] += value
else:
merged_dict[key] = value
# 输出结果
print("男生籍贯分布:", merged_dict)
print("女生籍贯分布:", dicGirls)
男生籍贯分布: {'Jiangsu': 11, 'Zhejiang': 7, 'Jilin': 1, 'Shandong': 5, 'Anhui': 4, 'Fujian': 2}
女生籍贯分布: {'Jiangsu': 3, 'Zhejiang': 2, 'Jilin': 1}