I am reading from a txt file: (it is formatted exactly like below)
(+1 +2 +3 +4)
(-4 -9)(-3 -6 -7)
My desired output is to have two (integer) lists
Both BEFORE the \\n and AFTER.
Example:
BEFORE_LIST = [1,2,3,4]
AFTER_LIST = [[-4,-9] , [-3, -6, -7]]
I can not figure out the correct combination of splits and strips to make this happen.
Any help I am very grateful.
listOfValues = (x.split(' ')for x in (val.replace(')','') for val in input().split('(')))
listOfIntegers = list(filter(None, [[int(value) for value in values if isInt(value)]for values in listOfValues]))
print(listOfIntegers)
The is isInt
method can be defined as:
def isInt(s):
try:
int(s)
return True
except:
return False
Or a more elaborate solution that avoids the exception:
def isInt(s):
return s.replace('+').replace('-').isdecimal() // doesn't cover all cases
This doesn't checks for invalid input format (For eg unmatched paranthesis).
Will it do?
import re
from ast import literal_eval
with open('test','r') as f:
for line in f:
line = line.replace(' ',',').replace('+','')
my_list = re.findall(r'\(.+?\)',line)
result = [list(literal_eval(i)) for i in my_list]
if len(result)==1:
result = [i for term in result for i in term ]
print result
Output:
[1, 2, 3, 4]
[[-4, -9], [-3, -6, -7]]
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.