python测试题 - 字典操作

字典操作

  • 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.有一个字典列表如下:
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}
]
print(max_price(portfolio))

输出结果为:

[{'name': 'AAPL', 'shares': 50, 'price': 543.22},
 {'name': 'ACME', 'shares': 75, 'price': 115.65},
  {'name': 'IBM', 'shares': 100, 'price': 91.1}]

手动换行的

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值