我正在写一个小练习程序来配对左右括号。如何减少嵌套for / if到一行?我试过了pure += [char for char in expression if char in brackets else '']
,但它没有用。这是我想要减少的完整代码。
def pair(expression):
left=("(","[","{")
right=(")","]","}")
brackets=left+right
print(brackets)
pure=''
#the part I want to reduce
for char in expression:
if char in brackets:
pure+=char
答案 0 :(得分:2)
这应该做你想要的
''.join([_ if _ in brackets else '' for _ in expression])
虽然正如其他人在评论中指出的那样,这根本没有任何意义。
全功能
def pair(expression):
left = ("(", "[", "{")
right = (")", "]", "}")
brackets = left + right
print(brackets)
pure = ''.join([_ if _ in brackets else '' for _ in expression])