我是Python的初学者。有人可以帮我解决下面我在python 2.7中的代码中出现的问题:
我试图以递归方式遍历列表和子列表,并删除列表中的AND,OR,NOT,IFF,IMPLIES。
我的方法:
def setOfSets(prop):
if isinstance(prop, str):
answer = prop
else:
for item in prop:
if isinstance(item, str):
if (item == IFF):
answer = prop.remove(item)
if (item == IMPLIES):
answer = prop.remove(item)
if (item == AND):
answer = prop.remove(item)
if (item == OR):
answer = prop.remove(item)
if (item == NOT):
answer = prop.remove(item)
else:
answer = setOfSets(item)
return answer
prop0 = setOfSets(inputList)
print "Set of Sets:"
print prop0
结果:
Input : ['or', 'R', ['not', 'B'], 'W']
Expected output : ['R',['B'],'W']
Current output : None
我认为我犯了一些愚蠢的错误或在python中使用了一些错误。
答案 0 :(得分:1)
构建新列表比复制旧的嵌套列表并从中删除项目更简单。
这是一个略有改进的版本,包含更多测试用例:
#!/usr/bin/env python
OPNAMES = set(('IFF', 'IMPLIES', 'AND', 'OR', 'NOT'))
def setOfSets(prop):
answer = []
for item in prop:
if isinstance(item, str):
if item.upper() not in OPNAMES:
answer.append(item)
else:
answer.append(setOfSets(item))
return answer
def test(prop):
print prop
print setOfSets(prop)
print
props = [
['A', 'B', 'C'],
['or', 'R', ['not', 'B'], 'W'],
['or', 'R', ['not', 'B'], [['IMPLIES', 'Q'], 'W'], 'Z'],
[['A', 'AND', ['B', 'OR', ['NOT', 'C']], 'IFF', 'D'],'IMPLIES', 'Z'],
]
for prop in props:
test(prop)
<强>输出强>
['A', 'B', 'C']
['A', 'B', 'C']
['or', 'R', ['not', 'B'], 'W']
['R', ['B'], 'W']
['or', 'R', ['not', 'B'], [['IMPLIES', 'Q'], 'W'], 'Z']
['R', ['B'], [['Q'], 'W'], 'Z']
[['A', 'AND', ['B', 'OR', ['NOT', 'C']], 'IFF', 'D'], 'IMPLIES', 'Z']
[['A', ['B', ['C']], 'D'], 'Z']