从Python中的列表中的元组获取值

时间:2018-03-23 04:24:47

标签: python python-3.x

x = Bookshop()
x.orders = [ [1, ("5464", 4, 9.99), ("8274",18,12.99), ("9744", 9, 44.95)],
[2, ("5464", 9, 9.99), ("9744", 9, 44.95)],
[3, ("5464", 9, 9.99), ("88112", 11, 24.99)],
[4, ("8732", 7, 11.99), ("7733", 11,18.99), ("88112", 5, 39.95)] ]

r1 = x.prodcut_price()
print(r1)

class Bookshop:

    def __init__(self):
        self.orders = 0
    def prodcut_price(self):
        result1  = list(map(lambda x:(x[1][0],x[1][1]*x[1][2]) if x[1][1]*x[1][2]>=100 else (x[1][0],x[1][1]*x[1][2]+10),self.orders))
        #print(result1)
        return result1

列表基本上是商店编号,每个商店出售一些包含代码,数量和价格的书。我正在尝试创建一种方法,将每个图书数量*价格并使用lambda在列表中的元组中打印,仅过滤和映射。我得到的是那个

[(' 5464',39.96),(' 5464',89.91),(' 5464',89.91),(' 8732&# 39;,83.93)]

但是我需要整个列表

1 个答案:

答案 0 :(得分:0)

要获取特定代码的总数,您可以执行以下操作:

代码:

def get_value(orders_list, code):
    return {order[0]: o[1] * o[2] for order in orders_list
            for o in order[1:] if o[0] == code}

测试数据:

orders = [
    [1, ("5464", 4, 9.99), ("8274", 18, 12.99), ("9744", 9, 44.95)],
    [2, ("5464", 9, 9.99), ("9744", 9, 44.95)],
    [3, ("5464", 9, 9.99), ("88112", 11, 24.99)],
    [4, ("8732", 7, 11.99), ("7733", 11, 18.99), ("88112", 5, 39.95)]
]

print(get_value(orders, '5464'))

结果:

{1: 39.96, 2: 89.91, 3: 89.91}