问题
Python 3: Given a string (an equation), return a list of positive and negative integers. I've tried various regex and list comprehension solutions to no avail.
Given an equation 4+3x or -5+2y or -7y-2x Returns: [4,3], [-5,2], [-7,-2]
input
str = '-7y-2x'
output
my_list = [-7, -2]
回答1:
Simple solution using re.findall function:
import re
s = '-5+2y'
result = [int(d) for d in re.findall(r'-?\d+', s)]
print(result)
The output:
[-5, 2]
-?\d+ - matches positive and negative integers
Raw string notation (
r"text") keeps regular expressions sane. Without it, every backslash ('\') in a regular expression would have to be prefixed with another one to escape it
回答2:
This regex should solve your problem.
[\+\-]?[0-9]+
Also, here is some code that goes with it.
import re
regex = re.compile(r'[\+\-]?[0-9]+')
nums = [int(k) for k in regex.findall('5-21x')]
来源:https://stackoverflow.com/questions/42751063/python-filter-positive-and-negative-integers-from-string