繁体   English   中英

遍历元组列表

[英]loop through list of Tuple

我有一个元组列表,我想遍历它并计算总成本。 我想得到橙色的总成本加上香蕉的总成本。 例如,使用5.26*8 + 2.00* 10找出总成本。

如何访问这些值? 我尝试5.26 using b[1]*b[2]访问例如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)

一种方法是每个元组解包到三个变量:

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

可以将整个计算写为单个生成器表达式

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( 或3.6 ),则应考虑使用dataclasses 如果您使用的是早期版本的Python,则可以选择collections.namedtuple

您在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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM