好的,所以我从 .txt 文件中读取了一个文本文件,该文件的格式如下:
home school 5
home office 10
home store 7
school store 8
office school 4
END OF FILE
然后我把它变成了python中的二维列表,它看起来像:
[['home', 'school', '5'], ['home','office','10'],['home','store','7'],
['school','store','8'], ['office','school','4']]
但我真正想要的方式是更多地采用字典格式,例如:
{'home': {'school': 5, 'office': 10, 'store': 7},
'school': {'store': 8},
'office': {'school': 4}}
这种格式看起来好多了,也更容易阅读。我拥有的数据更详细,但这是简单的版本。我已阅读我的文本文件如下:
myFileOpen = open(myInputFile, 'r')
myMap = myFileOpen.readlines()[:-1]
#Format the list, each line becomes a list in a greater list
myMap = [i.split('\n')[0] for i in myMap]
myMap = [i.split(' ') for i in myMap]
如果有人可以帮助解释如何做到这一点,我将不胜感激!谢谢!