比较python中的括号

Eli*_*eph 0 python python-2.7

from collections import Counter
x = '((()))'

print Counter(x)

Counter({')': 3, '(': 3})
Run Code Online (Sandbox Code Playgroud)

我需要比较我的字符串的开括号和括号是否相等.我用反击来做这件事.但是我应该如何比较计数器变量的两个值?

A.J*_*pal 5

您可以使用一个小功能,它使用.count():

>>> def checkparen(inp):
...     return inp.count('(') == inp.count(')') and inp.count('[') == inp.count(']') and inp.count('{') == inp.count('}')
... 
Run Code Online (Sandbox Code Playgroud)

因此:

>>> checkparen('((()))')
True
>>> checkparen('((())')
False
>>> checkparen('[ [ { { ( ( ) ) } } ] ]')
True
>>> 
Run Code Online (Sandbox Code Playgroud)

或者,使用collections.Counter:

>>> def checkparen(inp):
...     counter = collections.Counter(inp)
...     symbols = {'{':'}','[':']','(':')'}
...     for symbol in symbols:
...             if counter[symbol] != counter[symbols[symbol]]:
...                     return False
...     return True
... 
>>> checkparen('{')
False
>>> checkparen('[ [ { { ( ( ) ) } } ] ]')
True
>>> 
Run Code Online (Sandbox Code Playgroud)