반응형
'has_key' 개체에 'has_key' 특성이 없습니다.
Python에서 그래프를 통과하는 동안 a 다음 오류가 발생했습니다.
'has_key' 개체에 'has_key' 특성이 없습니다.
내 코드는 다음과 같습니다.
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if not graph.has_key(start):
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath: return newpath
return None
이 코드는 한 노드에서 다른 노드로 가는 경로를 찾는 것을 목표로 합니다.코드 출처: http://cs.mwsu.edu/ ~https/https/4883/https/https.https
이 오류가 발생하는 이유와 해결 방법은 무엇입니까?
has_key
Python 3에서 제거되었습니다.설명서에서 다음을 참조하십시오.
- 제거된
dict.has_key()
을 사용합니다.in
연산자를 대신합니다.
다음은 예입니다.
if start not in graph:
return None
python3에서,has_key(key)
로 대체됨__contains__(key)
python 3.7에서 테스트됨:
a = {'a':1, 'b':2, 'c':3}
print(a.__contains__('a'))
has_key는 Python 3.0에서 더 이상 사용되지 않습니다.또는 'in'을 사용할 수 있습니다.
graph={'A':['B','C'],
'B':['C','D']}
print('A' in graph)
>> True
print('E' in graph)
>> False
저는 그냥 사용하는 것이 "더 파이썬적"으로 간주된다고 생각합니다.in
에서와 같이 키가 이미 존재하는지 여부를 확인할 수 있습니다.
if start not in graph:
return None
시도:
if start not in graph:
자세한 내용은 ProgrammerShoped를 참조하십시오.
문서의 전체 코드는 다음과 같습니다.
graph = {'A': ['B', 'C'],
'B': ['C', 'D'],
'C': ['D'],
'D': ['C'],
'E': ['F'],
'F': ['C']}
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if start not in graph:
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath: return newpath
return None
작성 후 문서를 저장하고 F5를 누릅니다.
그런 다음 Python IDLE 셸에서 실행할 코드는 다음과 같습니다.
find_path(그래프, 'A', 'D')
IDLE에서 받아야 할 답변은 다음과 같습니다.
['A', 'B', 'C', 'D']
언급URL : https://stackoverflow.com/questions/33727149/dict-object-has-no-attribute-has-key
반응형
'programing' 카테고리의 다른 글
사용자가 양식 크기를 조정하지 못하도록 하려면 어떻게 해야 합니까? (0) | 2023.05.15 |
---|---|
업데이트 후 Eclipse/EGIT가 기존 리포지토리 정보를 인식하도록 하는 방법은 무엇입니까? (0) | 2023.05.15 |
VB.net 로 전환하는 가장 좋은 C# 변환기는 무엇입니까? (0) | 2023.05.15 |
기존 SQL Server 로그인을 동일한 이름의 기존 SQL Server 데이터베이스 사용자에 연결하는 방법 (0) | 2023.05.10 |
값을 기준으로 데이터 그리드 셀 색상 변경 (0) | 2023.05.10 |