-1

So I have several Lists of integers in a csv file like this:

["12345","325462"]

["214356","53645"]

...

I have to calculate the digit sum of every integer from the lists. After doing that I have to print the results like this:

"digit_sum1", "digit_sum2"

"digit_sum3", "digit_sum4"

...

The lists are in a .csv file. How can I keep the original formatation from the original list? Or how can I make the results print like that? The results also have to be in another .csv file.

This is my actual function:

def convert_raw_data(source, destination):

    with open(source) as fr, open(destination, "x") as fw:
        for line in fr:
            splitted_lines_0 = line.splitlines()
            for elem in splitted_lines_0:
                splitted_lines = elem.split(",")
                for numbers in splitted_lines:
                    sums = calculate_digit_sum(numbers)
                    fr.write(str(sums))

and the output of "sums" looks like this:

int1

int2

int3

...

And when printed in the csv file its all a long string.

Any help is appreciated.

ale
  • 1
  • 1

1 Answers1

1

I guess:

l1 = ["12345","325462"]
[sum([int(xx) for xx in list(x)]) for x in l1 ]

Which returns [15, 22]

Apply to each list, for example defining a method which also converts the sum to string, just in case:

def sum_digits_of_elements_in(lst):
  sums = [ sum([int(xx) for xx in list(x)]) for x in lst ]
  return [ str(x) for x in sums ]
  # return just sums to return integers

To be used as

l2 = ["214356","53645"]
sum_digits_of_elements_in(l2)
#=> ['21', '23']
iGian
  • 11,023
  • 3
  • 21
  • 36
  • 1
    The OP wants the results as a set of strings. So you could additionally put a `str()` around the `sum()` function. Then again, if everything is being written to .csv anyway, then it might not matter here. – Bill M. Dec 12 '18 at 22:00