简体   繁体   中英

How to sum a row of values from a text file using Python

I have rows of values in a text file which looks like this:

2,3,4,2
4,5,6,3
2,3,4,1

I want to be able to sum them in rows:

Eg,

row1 = 11
row2 = 18
row3 = 10

I have tried to add all the lines in a multi dimensional array, however I am having difficulties. I have tried the codes below:

allVotes=[]
fo=open('Votes.txt','r')

for line in fo:
  line=line.strip()
  parts=line.split(',')
  eachLine=int(line)
  allVotes.append(eachLine)
print(allVotes)

However, each line is not an integer. Any other ways to solve this?

You can not convert a list of strings to list of integers with int() call on that list, you need to convert each value separately since int() function accepts strings only.

To do that you can use list comprehensions or map function :

# List comprehension
eachLine = [int(s) for s in line]

# using map function
eachLine = list(map(int, line))

You can call sum() on these lists to get the sums. So, in your case results can be achieved by the following code:

fo=open('Votes.txt','r')

for line in fo:
    vote_sums = sum([int(s) for s in line.strip().split(',')])
    print(vote_sums)

Try this one:

fo=open('rank.txt','r')
for line in fo:
    l=list(map(int,line.split(",")))
    sm=sum(l[0:len(l)])
    print (sm)

sum(map(lambda x: int(x), raw_input().split(',')))

To get it into a 2-D array try this

all_values = []
with open('Votes.txt', 'rt') as file:
    for line in file:
        line = list(map(int, string.split(",")))
        all_values.append(line)

Or you could do something like this to get the sum of each line in a 1d array.

def get_results(filename):

    def sum_line(line):
        return sum(map(int, line.split(",")))

    with open(filename, 'rt') as file:
        return [sum_line(line) for line in file]

Using pandas we can do this in a single-row operation.

s = u"""2,3,4,2
4,5,6,3
2,3,4,1"""

import io
import pandas as pd

l = pd.read_csv(io.StringIO(s),header=None).sum(axis=1).tolist()
#l = pd.read_csv("path/to/file.csv",header=None).sum(axis=1).tolist()

l returns:

[11, 18, 10]

With pandas we can also export to dictionaries:

df = pd.read_csv(io.StringIO(s),header=None).sum(axis=1)
df.index = ("row {}".format(i+1) for i in range(len(df)))
d = df.to_dict()

d returns

{'row 1': 11, 'row 2': 18, 'row 3': 10}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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