如何将包含小数点的字符串转换为 python 中的列表
How to convert a string that includes decimal point to a list in python
输入的字符串是这样的
a=(2.5+6/3.7*2.09)
需要转换成列表才能用作计算器
b=['2.5','+','6','/','3.7','*','2.09']
如何将字符串 a 转换为类似 b 的列表,以便小数点数字被视为单个数字,而不像 ['2','.','0','9']
您可以这样做以获得结果
result = []
counter = 0
len_a = len(a)
symbol_list = ['*','(',')','+','-','/']
while counter < len_a:
helper = ''
if a[counter] not in symbol_list:
helper += a[counter]
else:
result.append(helper)
result.append(a[counter])
helper = ''
counter += 1
return result
您可以使用多个定界符拆分字符串:
import re
a="2.5+6/3.7*2.09"
print(re.split('\+|\*|/',a))
输出:
['2.5', '6', '3.7', '2.09']
完整解决方案:
import re
a="2.5+6/3.7*2.09"
pattern='\+|\/+|\*'
strings=re.split('\+|\*|/',a)
sym=re.findall(pattern,a)
new=[]
for i in range(len(strings)):
new.append(strings[i])
try:
new.append(sym[i])
except IndexError:
pass
print(new)
输出:
['2.5', '+', '6', '/', '3.7', '*', '2.09']
输入的字符串是这样的
a=(2.5+6/3.7*2.09)
需要转换成列表才能用作计算器
b=['2.5','+','6','/','3.7','*','2.09']
如何将字符串 a 转换为类似 b 的列表,以便小数点数字被视为单个数字,而不像 ['2','.','0','9']
您可以这样做以获得结果
result = []
counter = 0
len_a = len(a)
symbol_list = ['*','(',')','+','-','/']
while counter < len_a:
helper = ''
if a[counter] not in symbol_list:
helper += a[counter]
else:
result.append(helper)
result.append(a[counter])
helper = ''
counter += 1
return result
您可以使用多个定界符拆分字符串:
import re
a="2.5+6/3.7*2.09"
print(re.split('\+|\*|/',a))
输出:
['2.5', '6', '3.7', '2.09']
完整解决方案:
import re
a="2.5+6/3.7*2.09"
pattern='\+|\/+|\*'
strings=re.split('\+|\*|/',a)
sym=re.findall(pattern,a)
new=[]
for i in range(len(strings)):
new.append(strings[i])
try:
new.append(sym[i])
except IndexError:
pass
print(new)
输出:
['2.5', '+', '6', '/', '3.7', '*', '2.09']