我有一个元组列表,我想遍历它并计算总成本。我想得到橙色的总成本加上香蕉的总成本。例如,5.26*8 + 2.00* 10
找出总费用。
如何访问这些值?我尝试访问例如5.26 using b[1]*b[2]
,但出现错误。
def totalcost(shoping):
for a in shoping:
for b in a:
total1=b[1]*b[2]
print(total1)
shoping=[("orange",5.26,8),("banana",2.00,10)]
totalcost(shoping)
答案 0 :(得分:7)
一种方法是将每个元组解包为三个变量:
def get_total_cost(shopping):
total_cost = 0
for line_item in shopping:
product, cost, quantity = line_item # Unpack the tuple
total_cost += quantity * cost
return total_cost
shopping=[("orange", 5.26, 8), ("banana", 2.00, 10)]
print(get_total_cost(shopping))
一个人可以将解压缩与循环结合起来
def get_total_cost(shopping):
total_cost = 0
for product, cost, quantity in shopping:
total_cost += quantity * cost
return total_cost
可以将整个计算写为一个generator expression:
def get_total_cost(shopping):
return sum(quantity * cost for product, cost, quantity in shopping)
为清楚起见,我给product
起了一个名字。但是,在这样的代码中,习惯上用_
代替未使用的变量:
def get_total_cost(shopping):
return sum(quantity * cost for _, cost, quantity in shopping)
为完整起见,我将提到可以通过索引访问元组元素:
return sum(line_item[1] * line_item[2] for line_item in shopping)
尽管在我看来,这比使用命名变量的可读性要差得多。
最后,如果您使用的是Python 3.7(or 3.6),则应考虑使用dataclasses
。如果您使用的是Python的早期版本,则可以选择collections.namedtuple
。
答案 1 :(得分:0)
尝试以下代码段:
def totalcost(shoping):
shoping = [list(i) for i in shoping ]
x = 0
for i in shoping:
x += i[1]*i[2]
return x
shoping=[("orange",5.26,8),("banana",2.00,10)]
print(totalcost(shoping))
#62.08
答案 2 :(得分:0)
您在 a 中的 for 循环中有元组,以便可以从该元组中分割值。
def totalcost(shoping):
for a in shoping:
total1=a[1]*a[2]
print(total1)
shoping=[("orange",5.26,8),("banana",2.00,10)]
totalcost(shoping)