简体   繁体   中英

Converting a list of strings to a list of integers in Python

I have the following code which is used to extract a substring from each line of text on a file and put in a list of strings.

distribution = []

with open("./Output_Files/datafile.txt", "r") as fileRead:
         for line in fileRead:
             distr_chop = line.split()[3:]
             distribution.append(distr_chop)

Then I convert each string in the list to an integer:

distribution = [int(i) for i in distribution]

However, I get an error when printing the list.

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

  1. What is wrong with my code?
  2. What other way could I extract the substring directly to an integer?

distr_chop is a list.

If it is a single element list, you can do

...
distribution.append(distr_chop[0])

# then proceed to use the list comprehension to convert each element to an integer

dist_chop is in this case a list of 4th through nth "words" of the line thus distribution is an array of arrays which is not what I imagine you wanted.

use distribution += distr_chop if you actually wanted all the things after the 3rd or distribution.append(line.split())[3] if you just wanted just one element from each line

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