繁体   English   中英

当python中列表中的元素为“-”时,如何将当前元素与下一个元素合并?

[英]How to combine current element with the next element when elment is “-” in list in python?

我根据空间将字符串分成列表。 当元素值是“-”时,我想将其与下一个元素合并。

例如,

['x^3', 'x', '-', '4']想要转换为['x^3', 'x', '-4']

['-', 'x^3', 'x', '-', '4']想要转换为['-x^3', 'x', '-4']

    b = "x^3 + x - 4".split(" ")
    b = [x for x in b if x != '+']
    #combine "-" with next element

strreplace方法将很有用:

s = "x^3 + x - 4"
new_s = s.replace('- ', '-').replace('+ ', '')
b = new_s.split(" ")

这比使用for循环更优雅。
顺便说一句,如果可以使用列表理解,请避免使用for循环和list append ,因为重复调用append方法比列表理解要慢得多。

使用for循环,您可以执行以下操作:

l1 = ['x^3', 'x', '-', '4']
l2 = ['-','x^3', 'x', '-', '4']


def func(x):
    new_x = []
    temp = None
    for i in x:
        if temp:
            i = temp+i
            temp = None
        if i == '-':
            temp = "-"
            continue

        new_x.append(i)

    return new_x

print(func(l1))
print(func(l2))

输出:

['x^3', 'x', '-4']
['-x^3', 'x', '-4']

尝试这个:

def main(arr: list) -> list:
    """Combines '-' with next element in list"""

    for i in range(len(arr)):
        try:
            if arr[i] == '-':
                arr[i + 1] = '-' + arr[i + 1]

                arr[i] = ''
        except IndexError:
            pass

    while True:
        if '' in arr:
            arr.remove('')
        else:
            break

    return arr


print(main(['-', 'x^3', 'x', '-', '4']))

您也可以使用eval()进行计算:

b = "x**3 + x - 4"

x = 2

print(eval(b))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM