简体   繁体   English

遍历元组列表

[英]loop through list of Tuple

I have a list of a tuples and I want to iterate through it and calculate the total cost. 我有一个元组列表,我想遍历它并计算总成本。 I want to get the total cost of orange plus the total cost of the banana. 我想得到橙色的总成本加上香蕉的总成本。 For example, 5.26*8 + 2.00* 10 to find out the total cost. 例如,使用5.26*8 + 2.00* 10找出总成本。

How do I access these values? 如何访问这些值? I try to access for example 5.26 using b[1]*b[2] but I get an error. 我尝试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)

One way is to unpack each tuple into three variables: 一种方法是每个元组解包到三个变量:

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

One can combine the unpacking with the loop: 可以将解压缩与循环结合起来:

def get_total_cost(shopping):
    total_cost = 0
    for product, cost, quantity in shopping:
        total_cost += quantity * cost
    return total_cost

It is possible to write the entire computation as a single generator expression : 可以将整个计算写为单个生成器表达式

def get_total_cost(shopping):
    return sum(quantity * cost for product, cost, quantity in shopping)

I gave product a name for clarity. 为了清楚起见,我给product了个名字。 However, in code like this it is customary to see _ in place of unused variables: 但是,在这样的代码中,习惯上用_代替未使用的变量:

def get_total_cost(shopping):
    return sum(quantity * cost for _, cost, quantity in shopping)

For completeness, I'll mention that it is possible to access tuple elements by index: 为了完整起见,我将提到可以通过索引访问元组元素:

    return sum(line_item[1] * line_item[2] for line_item in shopping)

though to my eye this is significantly less readable than using named variables. 尽管在我看来,这比使用命名变量的可读性差得多。

Finally, if you're on Python 3.7 ( or 3.6 ) you should consider using dataclasses . 最后,如果您使用的是Python 3.7( 或3.6 ),则应考虑使用dataclasses If you're using an earlier version of Python, collections.namedtuple is an option. 如果您使用的是早期版本的Python,则可以选择collections.namedtuple

You have tuple in for loop in a so you can slice values from that tuple. 您在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