Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

Get values from a tuple in a list in Python

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

The list is basically the store number and each store sell some books with the code, quantity and the price.I am trying to create a method that will take each book quantity * price and print them in a tuple within list using lambda,filter and map only. what I got is that

[('5464', 39.96), ('5464', 89.91), ('5464', 89.91), ('8732', 83.93)]

but I need it for the whole list

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To get those totals for a specific code you can do:

Code:

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}

Test Data:

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'))

Results:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...