2

好的,所以我从 .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]

如果有人可以帮助解释如何做到这一点,我将不胜感激!谢谢!

4

4 回答 4

2

代码可能如下所示:

result = {}
for item in data:
    result.setdefault(item[0], {}).update({item[1]: item[2]})

完整代码证明:http: //ideone.com/8XUA41

于 2013-07-15T05:41:39.137 回答
1

跳过中间列表,一次完成所有操作:

d = {}

with open(myInputFile, 'r') as handle:
    for line in handle:
        if line == 'END OF FILE':
            continue

        key1, key2, value = line.split()

        if key1 not in d:
            d[key1] = {}

        d[key1][key2] = int(value)

您可以将最后一部分进一步压缩为:

d.setdefault(key1, {})[key2] = int(value)
于 2013-07-15T05:25:42.930 回答
1

黑客的答案是:

txt =\
'''
home school 5
home office 10
home store 7
school store 8
office school 4
'''

txt = txt.strip()
gs = [line.split(" ") for line in txt.split("\n")]
ts = {}
[ts.setdefault(x, {}).setdefault(y, z) for (x, y, z) in gs]
print ts
于 2013-07-15T05:33:19.297 回答
0

它很乱,但它适用于defaultdict

>>> from collections import defaultdict
>>> L = [['home', 'school', '5'], ['home', 'office', '10'], ['home', 'store', '7'], ['school', 'store', '8'], ['office', 'school', '4']]
>>> d = defaultdict(list)
>>> for i in L:
...     d[i[0]].append(i[1:])
...
>>> {k: dict(v) for k, v in d.items()} # Or d.iteritems with python 2.x
{'home': {'school': '5', 'store': '7', 'office': '10'}, 'school': {'store': '8'}, 'office': {'school': '4'}}

我对使用 defaultdicts 不是很有经验,所以可能有更好的方法。

于 2013-07-15T05:28:04.970 回答