In Python, what is the easiest way to find the smallest value in a list which contains both strings and floats? -


my code asks list of products or loads them file. then, need find of values smallest, , if there equally small elements, choose random one. however, still need link value relevant string. far have:

def checkprices(products):      x in range(len(products)):         if (x)%3 == 0:             name = str(products[x])             print(name)         elif (x+1)%3 == 0:             quantity = int(products[x])             print(quantity)             priceperunit = str(format(price/quantity, '.2f'))             print(name + " $" + priceperunit + " per unit")          elif (x)%1 == 0:                 price = float(products[x])                 print(price) 

how can extend can find smallest price per unit , print like:

i recommend product1 

i recommend instead of storing 3 values in flat list, seem be...

["product1", "3", "0.15", "product2", "4", "0.40"] 

...that instead store them list of tuples:

[("product1", 3, 0.15), ("product2", 4, 0.40)] 

this keeps logical grouping per-item, , lets things like...

product_info = [("product1", 3, 0.15), ("product2", 4, 0.40)] cheapest_product = min(product_info, key=lambda product: product[2] / product[1])  product_name, quantity, total_price = cheapest_product print "i recommend %s" % product_name 

note: if have flat list , want convert tuple list...

products = ["product1", "3", "0.15", "product2", "4", "0.40"] products_iter = iter(products) product_tuples = zip(products_iter, products_iter, products_iter) product_info = [(i[0], int(i[1]), float(i[2]) in product_tuples] 

and product_info list of tuples described above.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -