0

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?
6
  • 4
    Please do not SHOUT! It is considered rude. Commented Aug 29, 2020 at 2:37
  • 3
    distr_chop is a list Commented Aug 29, 2020 at 2:40
  • 2
    Using [3:] is a slice. It makes a list. Commented Aug 29, 2020 at 2:40
  • 2
    Try distribution.extend(distr_chop) Commented Aug 29, 2020 at 2:41
  • 2
    Each line is turned into a list. Do you want to keep that structure. Should each item in distribution be a list of the integers from that line? Commented Aug 29, 2020 at 2:42

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.