B.Joelene
B.Joelene

Reputation: 133

List and file operations in python

I have a file like this: (Dots are some numbers that were used to calculate the average.)

Ashe: .....
Azok: .....
Bumba: .....
Thrall: .....

And I have list averages with one entry for each row (first one is Ashe's; second one; Azok's...)

averages = [12.4, 44.8880001, 32.4, 97.701]

I split the names with this code:

for line in inp:
    line = line.split(": ")[0:1]

And when I tried to append each first elements of names and averages (second and second...):

for line in inp:
    line = line.split(": ")[0:1]
    #print(line)
    for d in averages:
        line.append(d)
    print(line)

I'm having output like this:

['Ashe', 12.4, 44.8880001, 32.4, 97.701]
['Azok', 12.4, 44.8880001, 32.4, 97.701]
['Bumba', 12.4, 44.8880001, 32.4, 97.701]
['Thrall', 12.4, 44.8880001, 32.4, 97.701]

However, expected output is that:

['Ashe', 12.4]
['Azok', 44.8880001]
['Bumba', 32.4]
['Thrall', 97.701]

What changes does my code require? Thank you in advance.

Upvotes: 2

Views: 66

Answers (2)

Mike Müller
Mike Müller

Reputation: 85442

You need iterate over each line and each average at the same time. The easiest way to do this is to use zip():

for line, avg in zip(inp, averages):
    line = line.split(":")[:1]
    line.append(avg)
    print(line)


['Ashe', 12.4]
['Azok', 44.8880001]
['Bumba', 32.4]
['Thrall', 97.701]

For example:

for value1, value2 in zip('abc', 'xyz'):
    print(value1, value2)

a x
b y
c z

Here the strings abc and xyz are zipped together, so that one element of each is used at a time.

In addition, tuple unpacking happens. Looping through the zipped strings actually gives you tuples:

for x in zip('abc', 'xyz'):
    print(x)

('a', 'x')
('b', 'y')
('c', 'z')

But in the first iteration, a and x are assigned value1, and value2:

>>> value1, value2 = ('a', 'x')
>>> value1
'a'
>>> value2
'x'

In the second:

>>> value1, value2 = ('b', 'y')
>>> value1
'b'
>>> value2
'y'

Upvotes: 1

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52143

You should map each name to each value in averages in the order they are placed in the list:

Assuming total number of names is equal to the length of averages list:

for index, line in enumerate(inp):
    line = line.split(": ")[0:1]
    line.append(averages[index])
    print(line)

Upvotes: 0

Related Questions