字典操作
1.字典a={“x”:1,“z”:3},b={“y”:2,“z”:4},请设计一个函My_Func(),
当My_Func(a,b)时输出c={“x”:1,“y”:2,“z”:3},
当My_Func(b,a)时输出c={“x”:1,“y”:2,“z”:4}
答案:
def My_Func(a, b):
c = a
for i in b.keys():
if i not in c:
c[i] = b[i]
return sorted(c.items(), key=lambda x: x[1])
输出结果为:
[(‘x’, 1), (‘y’, 2), (‘z’, 3)]
[(‘x’, 1), (‘y’, 2), (‘z’, 4)]
“”"
2.加班薪水问题:联邦法律规定如果员工每周的工作超过了40小时
那么多余的工作时间要支付1.5倍的薪水。
例如,如果一个人每小时的薪水是$12,
他一周工作了60小时,那么这个人的工资应该为:
(4012)+(1.512*(60-40))=$840
请编写一个程序,输入一个人一周的工作时间和每小时的薪水
输出一周的总薪水,格式如下:
“”"
def salary1(hour,s):
if hour <= 40:
return hour*s
else:
return (40*s)+(1.5*s*(hour-40))
print(salary1(110,12))
3.有一个字典列表如下:
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
name代表品牌名,shares代表分享数量,price代表价格
问题:请编写一个程序,输出价格最高的的前三个商品,
如:
[{'name': 'AAPL', 'price': 543.22, 'shares': 50},
{'name': 'ACME', 'price': 115.65, 'shares': 75},
{'name': 'IBM', 'price': 91.1, 'shares': 100}
]
答案如下:
def max_price(li):
li.sort(key=lambda x: x['price'],reverse=True)
li_max = []
for x in range(3):
li_max.append(li[x])
return li_max
```
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
输出结果为:
[{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'ACME', 'shares': 75, 'price': 115.65},
{'name': 'IBM', 'shares': 100, 'price': 91.1}]