### Python 中关于元组和字典的练习题
以下是几个涉及 Python 元组和字典的经典练习题及其解答:
#### 练习题 1:统计字符串中的大小写字母数量
编写一个函数 `fun`,接收一个字符串参数,返回一个元组 `(upper_count, lower_count)`,其中第一个值表示大写字母的数量,第二个值表示小写字母的数量。
```python
def fun(x):
upper_count = 0
lower_count = 0
for item in x:
if item.isupper():
upper_count += 1
elif item.islower():
lower_count += 1
else:
continue
return upper_count, lower_count
result = fun('ehllo WROLD')
print(result) # 输出应为 (5, 5)[^1]
```
---
#### 练习题 2:创建菜单字典并打印键值对
通过用户输入动态创建一个菜单字典 `menu_dict`,其键为食物名称,值为其对应的价格。最后分别打印所有的键和值。
```python
menu_dict = {}
while True:
try:
food = input("请输入食物名称(单独回车结束):")
if not food.strip(): # 如果输入为空,则退出循环
break
price = int(input("请输入价格:"))
menu_dict[food] = price
except ValueError:
print("输入有误,请重新输入!")
for k in menu_dict.keys(): # 打印所有键
print(f"食物名称: {k}")
for v in menu_dict.values(): # 打印所有值
print(f"价格: {v}")
```
此代码片段展示了如何利用异常处理机制来捕获非法输入,并实现动态构建字典的功能[^2]。
---
#### 练习题 3:查找特定模式的元素
给定三个容器(列表、元组、字典),找出以字母 `'a'` 或 `'A'` 开头且以 `'c'` 结尾的所有元素。
```python
li = ["alec", "aric", "Alex", "Tony", "rain"]
tu = ("alec", "aric", "Alex", "Tony", "rain")
dic = {'k1': "alex", 'k2': 'aric', "k3": "Alex", "k4": "Tony"}
list1 = list(tu)
list2 = list(dic.values())
newlist = li + list1 + list2
results = []
for i in newlist:
stripped_i = i.strip()
if (stripped_i.startswith('a') or stripped_i.startswith('A')) and stripped_i.endswith('c'):
results.append(stripped_i)
print(results) # 输出 ['alec', 'aric', 'alec', 'aric', 'aric'][^3]
```
---
#### 练习题 4:去除重复项的方法比较
提供两种方法用于从列表中去除重复项,一种基于字典去重,另一种基于集合去重。
##### 方法一:使用字典去重
```python
a_list = [1, 1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 3, 5, 2]
a_dic = {key: 0 for key in a_list}
ans = list(a_dic.keys())
print(ans) # 输出 [1, 2, 3, 4, 5, 6, 7][^4]
```
##### 方法二:使用集合去重
```python
a_list = [1, 1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 3, 5, 2]
ans = list(set(a_list))
print(ans) # 输出可能顺序不同,如 [1, 2, 3, 4, 5, 6, 7][^4]
```
---
#### 练习题 5:将数值分类存储到字典中
将一组整数分为两类,一类存入字典的一个键对应的值列表中,另一类存入另一个键对应的值列表中。
```python
data = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
dictionary = {}
greater_than_66 = []
less_than_66 = []
for value in data:
if value > 66:
greater_than_66.append(value)
elif value < 66:
less_than_66.append(value)
dictionary['k1'] = greater_than_66
dictionary['k2'] = less_than_66
print(dictionary) # 输出 {'k1': [77, 88, 99, 90], 'k2': [11, 22, 33, 44, 55]}[^5]
```
---
#### 练习题 6:模拟购物程序
设计一个简单的购物车功能,允许用户选择商品加入购物车,并判断总金额是否超出预算。
```python
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]
total_assets = int(input("请输入您的总资产:"))
shopping_cart = {}
cart_total_price = 0
for idx, product in enumerate(goods, start=1):
shopping_cart[idx] = product["name"]
print(shopping_cart)
while True:
choice = int(input("请选择要购买的商品编号(输入0结束选购):"))
if choice == 0:
break
selected_product_name = shopping_cart.get(choice)
if selected_product_name is None:
print("无效的选择,请重新输入!")
continue
selected_product_price = next(item["price"] for item in goods if item["name"] == selected_product_name)
cart_total_price += selected_product_price
print(f"已将{selected_product_name}加入购物车,总价目前为{cart_total_price}")
if cart_total_price > total_assets:
print("余额不足,无法完成购买!")
else:
print("购买成功!感谢惠顾!")[^5]
```
---
###