如何仅使用列表推导将简单表达式转换为Python中的列表?例如:
(1 + 2)应该是这样的
{["(", 1, "+", 2, ")"]
}
答案 0 :(得分:-2)
你可以试试这个:
s = '(1+2)'
new_s = [int(i) if i.isdigit() else i for i in s]
输出:
['(', 1, '+', 2, ')']
但是,对于更长,更复杂的字符串,使用re
进行标记化是更好的选择:
import re
from collections import namedtuple
s = "1.2 + 10"
token = namedtuple('token', ['type', 'value'])
grammar = r'\(|\)|\d+|\+|\.'
types = [('CPAREN', r'\)'), ('OPAREN', r'\('), ('DIGIT', r'\d+'), ('PLUS', '\+'), ('DOT', r'\.')]
final_types = [token([a for a, b in types if re.findall(b, i)][0], i) for i in re.findall(grammar, s)]
输出:
[token(type='DIGIT', value='1'), token(type='DOT', value='.'), token(type='DIGIT', value='2'), token(type='PLUS', value='+'), token(type='DIGIT', value='10')]