Python 如何在字典中搜索值和键?
所以我得到了这个图,我想在其中搜索。想象一下,我在葡萄牙,我想知道我可以访问多少个国家,所以从葡萄牙我可以去西班牙,然后去法国,然后我可以在德国和比利时之间选择。所以我想做的函数应该返回5,这是我可以访问的所有国家Python 如何在字典中搜索值和键?,python,python-3.x,Python,Python 3.x,所以我得到了这个图,我想在其中搜索。想象一下,我在葡萄牙,我想知道我可以访问多少个国家,所以从葡萄牙我可以去西班牙,然后去法国,然后我可以在德国和比利时之间选择。所以我想做的函数应该返回5,这是我可以访问的所有国家 graph = [["Portugal","Spain"],["Spain","France"],["France","Belgium","Germany"], ["Canada","United States"]] 我把图表转换成字典,得到了这个 def con
graph = [["Portugal","Spain"],["Spain","France"],["France","Belgium","Germany"],
["Canada","United States"]]
我把图表转换成字典,得到了这个
def convert(graph):
dic = {}
for lista in graph:
dic[lista[0]] = set()
for i in range(1,len(lista)):
dic[lista[0]].add(lista[i])
return dic
但我不知道该怎么办。你可以选择:
{'Canada': ['United States'], 'Spain':['France'], 'Portugal':['Spain'],
'France':['Belgium', 'Germany']}
产生
from itertools import dropwhile
graph = [["Portugal","Spain"],["Spain","France"],["France","Belgium","Germany"],["Canada","United States"]]
def get_destinations(start, lst):
# dropwhile discards any item that does not fulfill the predicate
# in this example it discards everything that has not start at the first position
rest = list(dropwhile(lambda x: x[0] != start, graph))
# here, we combine (zip) the rest with the next offset
# and compare the last item (len(item) - 1) with
# the first item of the next sublist
destinations = [y
for x, y in zip(rest, rest[1:])
if x[len(x) - 1] == y[0]]
# filter out duplicates and return the result
return {item for lst in destinations for item in lst}
destinations = get_destinations("Portugal", graph)
print(destinations)
首先,我们删除每个不等于
start
的项,然后收集最后一个子项等于下面第一个子项的项。最后,我们形成了一组子图。想象一下,在图中有另一个比利时元素,这样您也可以从比利时访问荷兰。在这种情况下,葡萄牙会有什么结果?那么结果会是6,因为从比利时你可以访问荷兰,还是仍然是5,因为如果你访问荷兰,你不能同时访问德国?嗯,很好啊,我想如果你访问荷兰,那么你可以回到比利时访问德国,但我不确定好的,谢谢你的帮助,我会使用你的代码,我会尽力理解它。理解这个函数很困难,因为我是这个领域的初学者pyhton@TBOTL:添加了一些解释。不是downvoter,而是x[0]不是start
非常脆弱;这是一个基于身份的测试,所以它只在两个字符串都被插入的情况下起作用(这会隐式地发生在许多字符串文本中,但不会应用于由I/O获取的随机字符串或从其他字符串构造的字符串)。您需要x[0]!=开始
,这是一个值比较,而不是身份比较。更次要的是,没有理由将生成器表达式传递给set
构造函数,只需使用集合理解:{item for lst in destinations for item in lst}
或使用chain
:set(itertools.chain.from_iterable(destinations))
{'France', 'Spain', 'Belgium', 'Germany'}