简体   繁体   中英

Convert string list to float list and then sum

Im just started to use python and need yours help please. I have a text file with 13 columns, in the 13's column I have numbers like 71.78 , 84.44 , 58.68 and etc.

I select the column and convert it to list:

['71.78', '84.44', '58.68', '70.15', '58.39']

after that I tried to convert to float to do a sum but it did not worked.

this is my code:

import csv
with open('cust.txt', 'r') as file: 
    file.readline()
    prices = [cols[13] for cols in csv.reader(file, delimiter="\t")]
    prices_list = (str(prices))
    floats = [float(x) for x in prices_list.split(" ")]
    print(sum(str(floats)))

I will be glad for help, thanks.

Update: My error is: ValueError: could not convert string to float: "['98.14',"

This should work.

prices = ['71.78', '84.44', '58.68', '70.15', '58.39']
floats = [float(x) for x in list]
print(sum(floats))

EDIT: Here is another approach reading the csv.

with open('cust.txt', 'r') as csvfile:
    prices = [cols[1] for cols in csv.reader(csvfile, delimiter="\t")]
    floats = [float(x) for x in prices]
    print(sum(floats))

To directly get a list of floats use just cast directly, when building the prices list.

with open('cust.txt', 'r', newline='') as csvfile:
    prices = [float(cols[1]) for cols in csv.reader(csvfile, delimiter=",")]
    print(sum(prices))

You only need this code to achieve what you want:

floats = [float(x) for x in prices_list]
print(sum(floats))

There are two problems with your code:

  1. if the CSV file has 13 columns, then the last column is cols[12] and not cols[13] .
  2. with prices_list = (str(prices)) you convert the whole list to one string (actually a tuple that contains only that string). In the next statement you are splitting this string using a space as separator, but that does not remove other characters such as the brackets, quotes and commas. That's why the conversion to float fails.

It helps to print the intermediate results (or use a debugger) to see what your program is doing and determine where the problem is.

The following code is a working example, assuming your CSV data is tab-delimited, has 13 columns, and the last column contains the floating point data you're interested in. Since I don't have your CSV file, I used a StringIO object with test data. A StringIO behaves just like a file, so the code should work the same with your CSV file.

#!/usr/bin/env python3

import csv
import io  # just for the test data since I don't have the CSV file

TEST_DATA = """
a\tb\tc\td\te\tf\tg\th\ti\tj\tk\tl\t71.78
a\tb\tc\td\te\tf\tg\th\ti\tj\tk\tl\t84.44
a\tb\tc\td\te\tf\tg\th\ti\tj\tk\tl\t58.68
"""

print(TEST_DATA)

#with open('cust.txt', 'r') as file:
with io.StringIO(TEST_DATA) as file:
    file.readline()
    prices_as_str = [cols[12] for cols in csv.reader(file, delimiter="\t")]
    print('prices_as_str: ' + repr(prices_as_str))
    prices_as_float = [float(x) for x in prices_as_str]
    # Alternatively you could use map():
    # prices_as_float = list(map(float, prices_as_str))
    print('prices_as_float: ' + repr(prices_as_float))
    print('sum: ' + repr(sum(prices_as_float)))

This has the following output (with tabs reduced to 6 characters to decrease line width):


a     b     c     d     e     f     g     h     i     j     k     l     71.78
a     b     c     d     e     f     g     h     i     j     k     l     84.44
a     b     c     d     e     f     g     h     i     j     k     l     58.68

prices_as_str: ['71.78', '84.44', '58.68']
prices_as_float: [71.78, 84.44, 58.68]
sum: 214.9

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