我正在python中实现BFS。为了将图的节点添加到队列中,我使用以下代码行:
graph = {}
graph['you'] = 'Alice','Bob','Claire'
search_queue+=graph['you']
完美地将我的键值存储为队列中的单独元素。但是,如果我的密钥只有一个值,例如graph['Alice'] = 'Peggy'
search_queue+=graph['Alice']
输出是一个队列,其中“ p”,“ e”,“ g”,“ g”,“ y”存储为单独的值。我知道应该使用append()将元素添加到队列或列表中,但是我需要为不同的键添加多个值和单个值。有没有办法做到这一点?到目前为止,我已经在graph['Alice'] = 'Peggy',
之类的值的末尾使用','来处理可以与队列或列表连接的键值,而不会丢失字符串。但是,我确信必须有更好的方法。这是我的代码-
from collections import deque
def congratulations_msg():
'''message to display success'''
print('Congratulations, we have found the element')
graph = {}
graph['you'] = 'Alice','Bob','Claire',
graph['Bob'] = 'Anuj','Peggy',
graph['Claire'] = 'Johnny','Thom',
graph['Alice'] = 'Peggy',
graph['Peggy']='you',
# Assign element to be searched
seller='Thom'
#Create a dequeue to store nodes
search_queue = deque()
# Initialize queue with values of 'you' key
search_queue+=graph['you']
checked_elements=[]
# Loop while queue is not empty
while search_queue:
print(search_queue)
#Check if element in queue already processed
if search_queue[0] in checked_elements:
search_queue.popleft()
continue
#Check if queue element is the one that we are looking for
elif seller == search_queue[0]:
congratulations_msg()
break
else:
#Store store processed queue element and add its nodes to the queue
checked_elements+= search_queue[0],
popped_element = search_queue.popleft()
checked_elements+= popped_element
search_queue+=graph.get(popped_element,'')
您可以定义一个小的函数来枚举正确的值。假设值元素是一个字符串或一个字符串列表
def get_values(element):
if isinstance(element, str):
# its a string
return element,
return element
# usage
search_queue += get_values(graph['alice'])
如果您不假设单个元素是字符串,则解决方案可能会涉及更多。您可以使用
>>> from collections.abc import Iterator
>>> isinstance('abc', Iterator)
False
>>> isinstance(('abc',), Iterator)
True
检查该值是否为嵌套迭代器。但是在那一点上,我会认真考虑如果dict值的类型不能同质,请仔细考虑。