如何解决如果输入具有相似的值,我如何从中返回多个结果
例如:在这种情况下,需要最昂贵的物品。
d= (('Shirts',40000),('trousers',('provisions',34000),('others',34000))
def pick_the_most_expensive_from_my_list(d):
material = ''
price = None
for x,y in d:
if price is None:
price= y
material= x
while y > price:
price = y
material= x
return material,price
解决方法
您可以先找到最高价格,然后返回具有该价格的对。
d= (('Shirts',40000),('trousers',('provisions',34000),('others',34000))
def pick_the_most_expensive_from_my_list(d):
return [pair for pair in d if pair[1]==max([item[1] for item in d])]
输出
[('Shirts',40000)]
,
你需要先找到最高价格,然后过滤掉有那么多价格的值。
d= (('Shirts',34000))
def pick_the_most_expensive_from_my_list(d):
if not d:
return None
max_v = max(d,key=lambda x:x[1])[-1]
return list(filter(lambda x: x[1]==max_v,d))
print(pick_the_most_expensive_from_my_list(d))
输出
[('Shirts',40000)]
或使用字典
d= (('Shirts',34000))
def pick_the_most_expensive_from_my_list(d):
if not d:
return None
price = {}
for i in d:
if i[1] not in price:
price[i[1]] = [i]
else:
price[i[1]].append(i)
return price.get(max(price))
print(list(pick_the_most_expensive_from_my_list(d)))
,
def mostExpensiveItems():
items = ['']
prices = [0]
for currentItems,currentPrices in items:
if currentPrices > prices[-1]:
items.append(currentItems)
prices.append(currentPrices)
elif currentPrices == prices[-1]:
items.append(currentItems)
prices.append(currentPrices)
print(items)
print(prices)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。