简体   繁体   中英

Converting a list of strings into integers

First, I have searched and found some other solutions that seem very plausible and should work, but for whatever reason after trying them with my data - those solutions don't work. I am using python 2.7.6

I am attempting to convert a list of strings into integers so I can add them.

#!/usr/bin/env python
import re
numlist = list()
total = 0
#open the file
f = open('c:/Users/Home/Documents/homework/python_webdata/regex_sum_21441.txt', 'r')

for line in f:
    line = line.rstrip()
    z= re.findall('[0-9]+', line)
    if z != []:
    numlist.append(z)


print numlist

#attempting to add up the int's from the list (which doesnt work) 
results = [int(i) for i in numlist]

total = sum(results)

My data prints out correctly, and looks something like this before I attempt to convert it to ints

[['2261'], ['2504', '4529'], ['3698', '2693', '3291'], ['3556', '9753', '4059'], ['113', '8261', '157'], ['8059', '1055'], ['1060'], ['2412', '1860'], ['3589'], ['3319'], ['475'], ['6802',

but I get the following error:

Traceback (most recent call last): File "C:\\Users\\Home\\Documents\\homework\\python_webdata\\lesson 2 code.py", line 20, in results = [int(i) for i in numlist] TypeError: int() argument must be a string or a number, not 'list'

As one of the comments put appropriately, you have list of lists containing integers because of the "append" you use.

Put

numlist.extend(z)

instead of

numlist.append(z)

Obviously, the issue here is with the z= re.findall('[0-9]+', line) as this will return a list of strings, now, after numlist.append(z) , you are appending the whole z list into numlist and that's why you get a list of list of strings.

Now,

results = [int(i) for i in numlist] will not work as you have in your numlist lists of strings and int(i) cannot convert a list into integers, you still have to flatten it, so, I think your best option is numlist.extend(z) to keep numlist flat with strings only (not a list of lists).

Another solution is to flatten your numlist this way:

results = [int(item) for lst in numlist for item in lst]

Note: As improvement to your code and sticking with best practices, it is better to use with open(file, mode) as f: as this will make sure that your file is closed without mentioning f.close() explicitly, this way:

with open('c:/Users/Home/Documents/homework/python_webdata/regex_sum_21441.txt', 'r') as f:
    for line in f:
        line = line.rstrip()
        z= re.findall('[0-9]+', line)
        if z != []:
            numlist.extend(z)

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