Mapping Names to Sequence Elements in Python

  • Python
  • 1 min read

Here is a Python program to map names to the sequence elements in Python.

Mapping Names to Sequence Elements in Python Using NAMEDTUPLE Library

The following Python program will map the names to the sequence of the columns and then will sum up the total.

from collections import namedtuple

Fruit = namedtuple('Fruit', ['name', 'pieces', 'price'])

def compute_cost(records):
    total = 0.0
    for rec in records:
        s = Fruit(*rec)
        total += s.pieces * s.price
    return total

# Some Data
records = [
    ('MANGO', 10, 45),
    ('APPLE', 10, 50),
    ('ORANGE', 20, 35)
]

print(compute_cost(records))

Output:

1650.0

See also: