programing

'has_key' 개체에 'has_key' 특성이 없습니다.

javamemo 2023. 5. 15. 20:57
반응형

'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_keyPython 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_keyPython 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

반응형