[英]How to extract value from tuple of tuples
I have list of this sort.我有这种清单。 It is the order list of a person:
这是一个人的订单列表:
orderList = [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)]
#Here the second value is the quantity of the fruit to be purchased
How do I extract the string and the float value separately?如何分别提取字符串和浮点值? I need to calculate the total order cost based on the given fruit prices:
我需要根据给定的水果价格计算总订单成本:
fruitPrices = {'apples':2.00, 'oranges': 1.50, 'pears': 1.75,
'limes':0.75, 'strawberries':1.00}
This is what I have tried:这是我尝试过的:
def buyLotsOfFruit(orderList):
"""
orderList: List of (fruit, numPounds) tuples
Returns cost of order
"""
totalCost = 0.0
length = len(orderList)
for i in range(0,length):
for j in range(0, length - i - 1):
totalCost += fruitPrices[orderList[i]] * orderList[j]
return totalCost
This yields wrong answer.这会产生错误的答案。 What am I doing wrong?
我究竟做错了什么? How can I fix this?
我怎样才能解决这个问题?
Thanks!谢谢!
You might use unpacking together with for
loop to get easy to read code, for example例如,您可以将解包与
for
循环一起使用以获得易于阅读的代码
orderList = [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)]
fruitPrices = {'apples':2.00, 'oranges': 1.50, 'pears': 1.75,
'limes':0.75, 'strawberries':1.00}
total = 0.0
for name, qty in orderList:
total += qty * fruitPrices[name]
print(total) # 12.25
Note ,
inside for
... in
so name
values become 1st element of tuple and qty
becomes 2nd element of tuple.请注意
,
在for
... in
, name
值成为元组的第一个元素,而qty
成为元组的第二个元素。
Just iterate the list of tuple, and multiply each quantity with their price and pass the iterator to sum
function to get total只需迭代元组列表,并将每个数量乘以它们的价格,然后将迭代器传递给
sum
函数以获得总计
total = sum(qty*fruitPrices.get(itm,0) for itm,qty in orderList)
# 12.25
How about?怎么样?
orderList = [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)]
fruitPrices = {'apples':2.00, 'oranges': 1.50, 'pears': 1.75,
'limes':0.75, 'strawberries':1.00}
order_total = 0.00
You can iterate over the list of tuples and use name
to get the fruit name and quantity
to get the quantity.您可以遍历元组列表并使用
name
获取水果名称和quantity
以获取数量。 Using that you can look up the price value of the fruit from the fruitPrices dictionary using the key and multiple by the quantity, totalling as you go:使用它,您可以使用 key 和乘以数量的倍数从 fruitPrices 字典中查找水果的价格值,然后总计:
for name, quantity in orderList:
order_total += fruitPrices.get(name, 0) * quantity
print(order_total)
Then into your function would look like this:然后进入您的函数将如下所示:
orderList = [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)]
fruitPrices = {'apples':2.00, 'oranges': 1.50, 'pears': 1.75,
'limes':0.75, 'strawberries':1.00}
def buyLotsOfFruit(orderList):
"""
orderList: List of (fruit, numPounds) tuples
Returns cost of order
"""
totalCost = 0.0
for name, quantity in orderList:
totalCost += fruitPrices.get(name, 0) * quantity
return totalCost
print(buyLotsOfFruit(orderList))
I change your code to don't get any errors.我更改了您的代码,以免出现任何错误。
Your orderList
is tuple you can accese each fruit_name
with [i][0]
and count with [i][1]
and for searching in dict
you can use dict.get(searching_key, value if not fount)
, You can change default value to any value you like, I set zero.您的
orderList
是元组,您可以使用[i][0]
访问每个fruit_name
并使用[i][1]
进行计数,并且对于在dict
中搜索,您可以使用dict.get(searching_key, value if not fount)
,您可以更改默认值到你喜欢的任何值,我设置为零。
def buyLotsOfFruit(orderList, fruitPrices):
totalCost = 0.0
length = len(orderList)
for i in range(0,length):
totalCost += fruitPrices.get(orderList[i][0], 0) * orderList[i][1]
return totalCost
buyLotsOfFruit(orderList, fruitPrices)
You can use functools.reduce
to summarize your code.您可以使用
functools.reduce
来总结您的代码。
>>> from functools import reduce
>>> reduce(lambda x,y : x+fruitPrices.get(y[0],0)*y[1], orderList, 0)
12.25
12.25
def buyLotsOfFruit(orderList, fruitPrices):
totalCost = 0.0
for order in orderList:
item, quantity = order
item_price = fruitPrices[item]
totalCost += (item_price * quantity)
return totalCost
Code:代码:
order_list = [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)]
fruit_prices = {'apples': 2.00, 'oranges': 1.50, 'pears': 1.75, 'limes': 0.75, 'strawberries': 1.00}
def buyLotsOfFruit(order_list, fruit_prices):
total_cost = 0
for i in order_list:
total_cost += fruit_prices[i[0]] * i[1]
return total_cost
print(buyLotsOfFruit(order_list, fruit_prices))
Output:输出:
12.25
Okay, so here is some explanation.好的,这里有一些解释。
for i in order_list:
i
is the current tuple in order_list eg: [('apples', 2.0)
. i
是 order_list 中的当前元组,例如: [('apples', 2.0)
。 So we can access it this way: i[0]
, we get apples
.i[0]
,我们得到apples
。 And we use string apples
to access apples price, you can imagine it this way: fruit_prices["apples"]
, and so we have price.apples
来获取苹果的价格,你可以这样想象: fruit_prices["apples"]
,所以我们有了价格。i[1]
which returns 2.0
in our exmaple with apples.i[1]
在我们的苹果示例中返回2.0
。 So you can image it looking like this:所以你可以把它想象成这样:
total_cost += price * amount
And also we could do我们也可以做
total_cost = total_cost + price * amount
but you can also use +=
operator to simplify the expression.但您也可以使用
+=
运算符来简化表达式。
Try this:尝试这个:
def buyLotsOfFruit(orderList):
"""
orderList: List of (fruit, numPounds) tuples
Returns cost of order
"""
fruitPrices = {'apples': 2.00, 'oranges': 1.50, 'pears': 1.75,
'limes': 0.75, 'strawberries': 1.00}
totalCost = 0.0
for item in orderList:
fruit, price = item[0], item[1]
totalCost += price
return totalCost
if __name__ == '__main__':
print(buyLotsOfFruit(orderList=[('apples', 2.0), ('pears', 3.0), ('limes', 4.0)])) # 9.0
To fully understand and visualise your data, you can use pandas:要完全理解和可视化您的数据,您可以使用 pandas:
import pandas as pd
orderList = [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)]
fruitPrices = {'apples':2.00, 'oranges': 1.50, 'pears': 1.75,
'limes':0.75, 'strawberries':1.00}
df = pd.DataFrame(orderList, columns = ['fruit', 'quantity'])
df['cost'] = df.apply( lambda row: row.quantity * fruitPrices[row.fruit], axis=1)
df
This returns:这将返回:
fruit quantity cost
0 apples 2.0 4.00
1 pears 3.0 5.25
2 limes 4.0 3.00
To get total cost: df['cost'].sum()
要获得总成本:
df['cost'].sum()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.