从内容中查找字典
Finding a dictionary from its contents
我正在尝试创建一些东西来证明用左手在墙上移动穿过迷宫的概念是可行的,所以我制作了一个 python 3.6 海龟程序来完成它。这是非常低效的,我知道,我是初学者,但我的问题是;
如何从字典的内容中找到字典的名称。
这是一个例子:
place1 = {"coordinates" : (150, 150), "filled_in": False}
place2 = {"coordinates" : (100, 100), "filled_in": True}
place3 = {"coordinates" : (50, 50), "filled_in": True}
turtle position = 50, 50
基本上是这样的
?["coordinates" : (50, 50), "filled_in" = True
我希望能够根据其中的值找到字典,这样我就可以检查它是否已填写。
if (dictionary containing value of "coordinates" : (50, 50))["filled_in"] = False:
do whatever
我知道我的格式可能有误,但在此先感谢您的帮助。
你可以将它们全部放在一个字典中,可以通过坐标索引:
place1 = {"coordinates" : (150, 150), "filled_in": False}
place2 = {"coordinates" : (100, 100), "filled_in": True}
place3 = {"coordinates" : (50, 50), "filled_in": True}
places = {p["coordinates"]: p for p in [place1, place2, place3]}
然后索引它:
>>> places[(50, 50)]['filled_in']
True
>>> places[(150, 150)]['filled_in']
False
只需检查字典的 'coordinates'
键:
for d in (place1, place2, place3):
if d['coordinates'] == (50, 50):
do_something()
我将详细说明@MSeifert 的回答。假设您有 64 个变量,如下所示:
place1, place2, ..., place64
只需替换为:
places = {p["coordinates"]: p for p in [place1, place2, place3]}
与:
places_list = ["place{}".format(num) for num in range(1, 65)]
places64 = eval(str(places_list))
places = {p["coordinates"]: p for p in places64}
也就是说,使用 eval is a bad practice。例如,考虑从单独的文件加载坐标。
我正在尝试创建一些东西来证明用左手在墙上移动穿过迷宫的概念是可行的,所以我制作了一个 python 3.6 海龟程序来完成它。这是非常低效的,我知道,我是初学者,但我的问题是; 如何从字典的内容中找到字典的名称。
这是一个例子:
place1 = {"coordinates" : (150, 150), "filled_in": False}
place2 = {"coordinates" : (100, 100), "filled_in": True}
place3 = {"coordinates" : (50, 50), "filled_in": True}
turtle position = 50, 50
基本上是这样的
?["coordinates" : (50, 50), "filled_in" = True
我希望能够根据其中的值找到字典,这样我就可以检查它是否已填写。
if (dictionary containing value of "coordinates" : (50, 50))["filled_in"] = False:
do whatever
我知道我的格式可能有误,但在此先感谢您的帮助。
你可以将它们全部放在一个字典中,可以通过坐标索引:
place1 = {"coordinates" : (150, 150), "filled_in": False}
place2 = {"coordinates" : (100, 100), "filled_in": True}
place3 = {"coordinates" : (50, 50), "filled_in": True}
places = {p["coordinates"]: p for p in [place1, place2, place3]}
然后索引它:
>>> places[(50, 50)]['filled_in']
True
>>> places[(150, 150)]['filled_in']
False
只需检查字典的 'coordinates'
键:
for d in (place1, place2, place3):
if d['coordinates'] == (50, 50):
do_something()
我将详细说明@MSeifert 的回答。假设您有 64 个变量,如下所示:
place1, place2, ..., place64
只需替换为:
places = {p["coordinates"]: p for p in [place1, place2, place3]}
与:
places_list = ["place{}".format(num) for num in range(1, 65)]
places64 = eval(str(places_list))
places = {p["coordinates"]: p for p in places64}
也就是说,使用 eval is a bad practice。例如,考虑从单独的文件加载坐标。