2017-01-04 5 views
1

로그인 변경 if 문을 원합니다. 나는 간부Python에서 exec를 사용하여 IndexError 가져 오기

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] 

이 작동 얻을.

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

exec("if array {} column: kar_map[index1][index2]=1".format(equal)) 

을 변경해야합니다,하지만 당신은 왜 비 간부 코드 대신'exec'을 사용하고 있습니까? – mgilson

+1

먼저이 방법으로 exec를 사용하지 마십시오. 상당히 휘발성이 있으며 이와 같은 문제가 발생할 수 있습니다. 'pattern_map'과 'array'예제를 게시하여 로컬에서 디버깅 할 수 있습니까? – ospahiu

답변

0

단일 행 if 문을 사용하는 경우 실행하려는 코드 뒤에 if 부분을 넣습니다. 또한 .format(equal)은 의미가 없습니다. 당신이 원하는 것은 무엇입니까? 등호 (=)를 변경하려면 .format(equals = equal)을 사용하고 ={equals}으로 변경해야합니다. 당신은 어쩌면 바보 같은 질문이다

exec("kar_map[index1][index2] {equals} 1 if array {} column".format('=' = equal))