Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 计算字符串中括号之间的数字_Python_Python 3.x_String - Fatal编程技术网

Python 计算字符串中括号之间的数字

Python 计算字符串中括号之间的数字,python,python-3.x,string,Python,Python 3.x,String,我有一根像这样的绳子 "(1 4 3 2 12 7 10 5)(9 11)(4 3 2 3 2 1)" 有没有一种方法可以让我数一数两个括号之间的数字,然后得到一个如下的列表 [8,2,6] 其中8=计算数字量的第一个括号的长度?这里有一种方法,使用a获得括号之间数字的字符串列表,并使用列表理解来计算其中的数字: s = '(1 4 3 2 12 7 10 5)(9 11)(4 3 2 3 2 1)' import re l = re.findall(r'\(((?:\d+\s*)+)\)'

我有一根像这样的绳子

"(1 4 3 2 12 7 10 5)(9 11)(4 3 2 3 2 1)"
有没有一种方法可以让我数一数两个括号之间的数字,然后得到一个如下的列表

[8,2,6]
其中8=计算数字量的第一个括号的长度?

这里有一种方法,使用a获得括号之间数字的字符串列表,并使用列表理解来计算其中的数字:

s = '(1 4 3 2 12 7 10 5)(9 11)(4 3 2 3 2 1)'
import re
l = re.findall(r'\(((?:\d+\s*)+)\)', s)
# ['1 4 3 2 12 7 10 5', '9 11', '4 3 2 3 2 1']
[len(i.split()) for i in l]
# [8, 2, 6]

这里有一个简单的解决方案

def getlist(input_string):
    output = []
    count = 0
    for i in range(1, len(input_string)-1):
        char = input_string[i]
        if char == "(" :
            output.append(count)
            count = 0
        if char.isdigit() and not input_string[i+1].isdigit():
            count += 1
    output.append(count)
    return output

您可以对每次出现的开括号和闭括号进行拆分(即“)(”然后对每个空格进行拆分)

def get_lengths(s):
    list1=s.split(")(")
    return [len(x.split()) for x in list1]

s=input()
print(get_lengths(s))

你听说过吗?我没有。有模块吗?是的模块!ans=[len(I.split(“”)代表我在'(1 4 3 2 12 7 10 5)(9 11)(4 3 2 3 2 1)'。split(')(')以这种方式编码数据似乎很愚蠢…为什么你一开始就有这样的字符串,你能控制它吗?