Michaels
Michaels

Reputation: 41

How do I separate name and sum of numbers?

I'm struggling to add those numbers together and put names apart. So, I need to print each line containing names and total numbers.

e.g. Peter Jones: 155

File 'test1.txt' example:

Marshall Rogers, 88, 21, 90
Richard Lao, 30
Peter Jones, 23, 54,78
AABB CC EE RR rest, 90, 3, 3, 4

Here's my code:

def find_their_numbers(files):
    """print it out"""
    file = open(files)
    lines = file.read().splitlines()
    nam = ""
    new_list = []
    for name in lines:
        names = name.split(',')
        for i in range(len(names)):
            if i == 0:
                print(names[i] + ':', end='')
            if i > 0:
                print(names[i])
find_their_numbers('test1.txt')

Upvotes: 1

Views: 70

Answers (3)

Alain T.
Alain T.

Reputation: 42143

You can use unpacking to separate the name from the rest of the components:

with open(fileName,'r') as file:
    for line in file.readLines():
        name,*numbers = line.split(',')
        print(name + ":", sum(map(int,numbers)))

Upvotes: 0

RMPR
RMPR

Reputation: 3521

You can do that without finding individually each number:

def find_their_numbers(text_file):
    with open(text_file) as f:
        lines = f.read().splitlines()
        for line in lines:
            line_split = line.split(',')
            name = line_split[0]
            total = sum([int(x) for x in line_split[1:]])
            print(name + ": " + str(total))

Sample test:

>>> find_their_numbers('test1.txt')
rshall Rogers: 199
Richard Lao: 30
Peter Jones: 155
AABB CC EE RR rest: 100

Upvotes: 1

Gabio
Gabio

Reputation: 9494

Try this:

file = open(files)
lines = file.read().splitlines()
for name in lines:
    names = name.split(',')
    print(f"{names[0]}: {sum(map(int,names[1:]))}")

where sum(map(int,names[1:])) will slice names from the second element, convert all the elements to integers and sum them.

Upvotes: 1

Related Questions