from collections import Counter
x = '((()))'
print Counter(x)
Counter({')': 3, '(': 3})
Run Code Online (Sandbox Code Playgroud)
我需要比较我的字符串的开括号和括号是否相等.我用反击来做这件事.但是我应该如何比较计数器变量的两个值?
您可以使用一个小功能,它使用.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)
| 归档时间: |
|
| 查看次数: |
438 次 |
| 最近记录: |