显示嵌套列表中存储的商品的最大价格和数量

时间:2019-03-26 11:30:26

标签: python

我正在尝试找出一种从嵌套列表中获取最高价格和最低数量的方法

第一个数字是价格,第二个数字是数量 因此,在“ mouse,10,50”

中,价格为10,数量为50
items=[["mouse,10,50"],["pen,20,50"],["pencil,30,30"],["sharpner,40,40"],["ruler,50,10"]]
max_price=max(items)

6 个答案:

答案 0 :(得分:0)

尝试

items=[["mouse,10,50"],["pen,20,50"],["pencil,30,30"],["sharpner,40,40"],["ruler,50,10"]]
max_price = 0
min_quantity = 1000000
for item in items:
  temp = item[0].split(',')
  if int(temp[1]) > max_price:
    max_price = int(temp[1])
  if int(temp[2]) < min_quantity:
    min_quantity = int(temp[2])
print(max_price)
print(min_quantity)

输出

50
10

答案 1 :(得分:0)

使用mathlowQty分配无穷大,并使用split()从列表中的元素获取索引值:

import math

items=[["mouse,10,50"],["pen,20,50"],["pencil,30,30"],["sharpner,40,40"],["ruler,50,10"]]   
maxPrice = 0
lowQty = math.inf

for elem in items:
    maxPrice = max(maxPrice, int(elem[0].split(",")[1]))
    lowQty = min(lowQty, int(elem[0].split(",")[2]))

print("max_price: {}".format(maxPrice))
print("lowest_qty: {}".format(lowQty))

缩略语版

print("max_price: {}".format(max([int(elem[0].split(",")[1]) for elem in items])))
print("lowest_qty: {}".format(min([int(elem[0].split(",")[2]) for elem in items])))

输出

max_price: 50
lowest_qty: 10

答案 2 :(得分:0)

from operator import itemgetter    
items=[["mouse,10,50"],["pen,20,50"],["pencil,30,30"],["sharpner,40,40"],["ruler,50,10"]]
temp_list = []

for i in range(0,len(items)):
    temp_list.append(items[i][0].split(","))

reverse_sorted_element= sorted(temp_list,key=itemgetter(2),reverse = True)
max_price  = reverse_sorted_element[0][2]

sorted_element= sorted(temp_list,key=itemgetter(2))
lowest_qty  = sorted_element[0][2]

print("max_price: {}".format(max_price))
print("lowest_qty: {}".format(lowest_qty))

输出

max_price: 50
lowest_qty: 10

答案 3 :(得分:0)

我能想到的最简单的方法是:

items=[["mouse,10,50"],["pen,20,50"],["pencil,30,30"],["sharpner,40,40"],["ruler,50,10"]]
max_price = max([int(i[0].split(",")[1]) for i in items])
min_quantity = min([int(i[0].split(",")[2]) for i in items])

print(max_price)
print(min_quantity)

答案 4 :(得分:0)

您最终可以在re字符上使用split,

>>> import re
>>> items
[['mouse,10,50'], ['pen,20,50'], ['pencil,30,30'], ['sharpner,40,40'], ['ruler,50,10']]
>>> y = max(items, key=lambda x: map(int, re.findall(r'\d+', x[0])))
>>> y
['ruler,50,10']
>>> z = y[0].split(',')
>>> z
['ruler', '50', '10']
>>> max_price, low_qty = map(int, z[1:])
>>> max_price, low_qty
(50, 10)

答案 5 :(得分:0)

这是您的解决方案

您可以将代码放入函数中,并可以将项目作为参数传递

from math import inf as INFINITY

    items=[["mouse,10,50"],["pen,20,50"],["pencil,30,30"],["sharpner,40,40"],["ruler,50,10"]]

    max_price= 0
    min_quant = INFINITY


    for List in items:
        string = List[0]

    name,quant,price = st.split(',')
    quant,price = int(quant),int(price)

    if quant<min_quant:
        min_quant = quant

    if price > max_price:
        max_price = price

print("max price is",max_price)
print("min quant is",min_quant)