【问题标题】:Converting string of letters and numbers into array将字母和数字的字符串转换为数组
【发布时间】:2021-01-20 15:23:43
【问题描述】:

我对 python 很陌生,但我想将一个包含数字和字母的字符串转换为一个数组。有什么方法可以让数字不带字符串并将字母保持为字符串?

示例:string = "2A3M4D8"

我希望 A 是两边的加法数字。 M要乘,D,除,S,减。所以程序应该计算 ((2+3)*4)/8=2,5

import numpy as np
def compile(program):
    program=map(int,program())

    newvector=np.array([])

    for i in range(len(program)):
        if program[i]=="A":
            R=program[i-1]+program[i+1]
            
        elif program[i]=="S":
            R=program[i-1]-program[i+1]
        
        elif program[i]=="M":
            R=program[i-1]*program[i+1]
            
        elif program[i]=="D":
            R=program[i-1]/program[i+1]
            
            newvector=np.concatenate(newvector,R)
    
        result=sum(newvector)
    
    return result

print(compile("3A3"))

【问题讨论】:

  • 您尝试过什么吗?遇到了什么错误?
  • 听起来你可以用'+'等替换'A',使用str.translate之类的东西,然后使用something like this来评估最终表达式。
  • 我尝试使用 map(int) 然后设置 op a forloopis 但我只收到 0 作为输出。
  • 我刚刚用我的代码更新了这个问题^^
  • 请始终格式化代码/回溯/数据 - 选择它并输入 ctrl-kFormatting help...Formatting sandbox

标签: python arrays string


【解决方案1】:
s = '2A3M4D8'
    s = re.split('(\d+)', s)
    s = list(filter(None, s))
    print(s)

    stack = []
    res = 0
    letter = ''

    for x in s:
        if x.isnumeric():
            stack.append(int(x))
            if letter != '':
                print(stack)
                if letter == 'M':
                    res = stack[0] * stack[1]
                elif letter == 'A':
                    res = stack[0] + stack[1]
                elif letter == 'D':
                    res = stack[0] / stack[1]
                stack = []
                print(res)
                stack.append(res)
                print(stack)
                res = 0
                letter = ''
        else:
            letter = x
    print(stack[0])

【讨论】:

  • 但我认为我的问题是当数字显示为字符串时我无法计算数字?
  • Python 是一种低级语言,这意味着您不能拥有由 int 和 string 组成的数组。我将通过解决方法更新我的答案。
  • @Jules Spender 你不能有一个由 int 和 string 组成的数组你是在谈论 np.array 还是原生 python 列表?
  • 我真的不确定哈哈,但谢谢,我认为这对我有很大帮助
  • 您可以考虑拆分运算符 r'([ASMD])',以防 程序 中有浮点数,例如'2.2A3.3M4.4'.
【解决方案2】:
import re

string="2A3M4D8"

string = re.sub(r"([0-9]+)A([0-9]+)",'('+r'\1'+'+'+r'\2'+')',string)

string = re.sub(r"M","*",string)

string = re.sub(r"D","/",string)

print (eval(string))

输出:

2.5

您使用re.sub() 来正确格式化操作优先级并用数学运算符替换字母运算符。然后你eval() 得到它。

【讨论】:

  • 我刚刚用 mu 代码更新了我的问题。我很高兴你回答,但我不确定我知道这个功能是如何工作的。也许你可以帮助我的forloop?
【解决方案3】:

您也可以使用 replace 将 A、M、D、S 替换为运算符,然后在获得包含运算符的字符串并计算相同的值后放入括号。

j='2A3M4D8'
for i in j:
    if i == 'A':
        j = j.replace('A','+')
    if i == 'M':
        j = j.replace('M','*')
    if i == 'D':
        j = j.replace('D','/')
    if i == 'S':
        j = j.replace('S','-')

count = 0
a = '('
b = ')'
arr = []
for i in j:
    if i.isdigit() and count%2 == 0:
        i = a + i
        arr.append(i)
    elif i.isdigit() and count%2 == 1:
        i = i + b
        arr.append(i)
    else:
        arr.append(i)
        count -= 1
        
    count += 1
        

print (eval(''.join(arr)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 2018-02-01
    • 2019-12-01
    • 1970-01-01
    • 2012-01-10
    相关资源
    最近更新 更多