I have a text file with some plain numbers that i want them as integers in a list.
For example i'd like this
299 314 427
to be converted to this
list = [[299], [314], [427]]
i read the text file
with open('C:/...', 'r') as f:
masses= f.read()
and then i use a for loop and spectra.split(' ') since a blank space is the only thing that separates the integers but it appeds to list every number separately
list = []
masses.split(' ')
for mass in masses:
list.append(mass)
the results is ['2','9','9',' ','3',......] how can i split them and append them in list ?
Using list comprehension:
>>> with open('FILEPATH') as f:
... lst = [[int(n)] for n in f.read().split()]
...
>>> lst
[[299], [314], [427]]
Without argument, str.split
splits strings by consecutive whitespace (space, tab, newline, ..):
>>> 'a\t\tb\nc d'.split()
['a', 'b', 'c', 'd']
>>> 'a\t\tb\nc d'.split(' ')
['a\t\tb\nc', '', 'd']
Don't use list
as a variable name. It shadows the builtin function list
.
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.