我希望更改登录if语句。当我使用exec
时def set_value(array, negation=False):
equal = "!=" if negation else "=="
for index1, row in enumerate(pattern_map):
for index2, column in enumerate(row):
exec("if array {} column: kar_map[index1][index2]=1".format(equal))
我得到IndexError
Traceback (most recent call last):
File "/home/charlie/Desktop/Projects/Python/karnaugh_map.py", line 234, in <module>
print(kar_map.map_filled)
File "/home/charlie/Desktop/Projects/Python/karnaugh_map.py", line 176, in map_filled
kar_map = self.__class__.filled_map_1(self.__table.count_variable, self.map_pattern, kar_map, variable)
File "/home/charlie/Desktop/Projects/Python/karnaugh_map.py", line 160, in filled_map_1
set_value("")
File "/home/charlie/Desktop/Projects/Python/karnaugh_map.py", line 148, in set_value
exec("if array {} column: kar_map[index1][index2]=1".format(equal))
File "<string>", line 1, in <module>
TypeError: 'Map' object does not support indexing
[Finished in 0.1s with exit code 1]
[cmd: ['/usr/bin/python3.5', '-u', '/home/charlie/Desktop/Projects/Python/karnaugh_map.py']]
[dir: /home/charlie/Desktop/Projects/Python]
[path: /usr/local/sbin:/usr/local/bin:/usr/bin:/usr/lib/jvm/default/bin:/opt/ope ncascade/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl]
当我不使用exec时,它可以正常工作。
def set_value(array, negation=False):
for index1, row in enumerate(pattern_map):
for index2, column in enumerate(row):
if negation:
if array != column:
kar_map[index1][index2] = 1
else:
if array == column:
kar_map[index1][index2] = 1
任何人都知道这个问题是什么?
答案 0 :(得分:0)
使用单行if语句时,将if
部分放在要运行的代码之后。另外,.format(equal)
没有意义。你想要的是什么?如果您要更改等号(=),则应使用.format(equals = equal)
并将=
更改为{equals}
。你应该改变
exec("if array {} column: kar_map[index1][index2]=1".format(equal))
到
exec("kar_map[index1][index2] {equals} 1 if array {} column".format('=' = equal))